text
stringlengths
54
60.6k
<commit_before>#include <ModuleDefines.hpp> #include <Extension.hpp> namespace Module { /** * An extension that incorporates bullet physics into the Module Game Engine. */ class Physics : Extension { // IMPLEMENT THESE // virtual const std::string& getName() { return "Bullet Physics Extension"; } virtual const std::string& getVersion() { return "0.0.1"; } // These functions are for organizing the instantiation of callbacks and threads virtual void attachGraphicsCallbacks() {} virtual void attachInputCallbacks() {} virtual void attachAudioCallbacks() {} virtual void spawnThreads(); }; }<commit_msg>More work on physics extension<commit_after>#ifndef __PHYSICS_HPP__ #define __PHYSICS_HPP__ #include <ModuleDefines.hpp> #include <Extension.hpp> namespace Module { /** * An extension that incorporates bullet physics into the Module Game Engine. */ class Physics : Extension { // IMPLEMENT THESE // virtual const std::string& getName() { return "Bullet Physics Extension"; } virtual const std::string& getVersion() { return "0.0.1"; } // These functions are for organizing the instantiation of callbacks and threads virtual void attachGraphicsCallbacks() {} virtual void attachInputCallbacks() {} virtual void attachAudioCallbacks() {} virtual void spawnThreads(); }; } #endif<|endoftext|>
<commit_before>#include "cnn/edges.h" #include "cnn/cnn.h" #include "cnn/training.h" #include <boost/archive/text_oarchive.hpp> #include <iostream> #include <fstream> using namespace std; using namespace cnn; int main(int argc, char** argv) { cnn::Initialize(argc, argv); // parameters const unsigned HIDDEN_SIZE = 8; const unsigned ITERATIONS = 30; Model m; SimpleSGDTrainer sgd(&m); //MomentumSGDTrainer sgd(&m); Parameters& p_a = *m.add_parameters(Dim({1})); Parameters& p_b = *m.add_parameters(Dim({HIDDEN_SIZE})); Parameters& p_W = *m.add_parameters(Dim({HIDDEN_SIZE, 2})); Parameters& p_V = *m.add_parameters(Dim({1, HIDDEN_SIZE})); // build the graph Hypergraph hg; // get symbolic variables corresponding to parameters VariableIndex i_b = hg.add_parameter(&p_b); VariableIndex i_a = hg.add_parameter(&p_a); VariableIndex i_W = hg.add_parameter(&p_W); VariableIndex i_V = hg.add_parameter(&p_V); vector<float> x_values(2); // set x_values to change the inputs to the network VariableIndex i_x = hg.add_input(Dim({2}), &x_values); cnn::real y_value; // set y_value to change the target output VariableIndex i_y = hg.add_input(&y_value); // two options: MatrixMultiply and Sum, or Multilinear // these are identical, but Multilinear may be slightly more efficient #if 0 VariableIndex i_f = hg.add_function<MatrixMultiply>({i_W, i_x}); VariableIndex i_g = hg.add_function<Sum>({i_f, i_b}); #else VariableIndex i_g = hg.add_function<Multilinear>({i_b, i_W, i_x}); #endif VariableIndex i_h = hg.add_function<Tanh>({i_g}); #if 0 VariableIndex i_p = hg.add_function<MatrixMultiply>({i_V, i_h}); VariableIndex i_y_pred = hg.add_function<Sum>({i_p, i_a}); #else VariableIndex i_y_pred = hg.add_function<Multilinear>({i_a, i_V, i_h}); #endif hg.add_function<SquaredEuclideanDistance>({i_y_pred, i_y}); hg.PrintGraphviz(); if (argc == 2) { ifstream in(argv[1]); boost::archive::text_iarchive ia(in); ia >> m; } // train the parameters for (unsigned iter = 0; iter < ITERATIONS; ++iter) { double loss = 0; for (unsigned mi = 0; mi < 4; ++mi) { bool x1 = mi % 2; bool x2 = (mi / 2) % 2; x_values[0] = x1 ? 1 : -1; x_values[1] = x2 ? 1 : -1; y_value = (x1 != x2) ? 1 : -1; loss += as_scalar(hg.forward()); hg.backward(); sgd.update(1.0); } sgd.update_epoch(); loss /= 4; cerr << "E = " << loss << endl; } boost::archive::text_oarchive oa(cout); oa << m; } <commit_msg>use better interface<commit_after>#include "cnn/edges.h" #include "cnn/cnn.h" #include "cnn/training.h" #include <boost/archive/text_oarchive.hpp> #include <iostream> #include <fstream> using namespace std; using namespace cnn; int main(int argc, char** argv) { cnn::Initialize(argc, argv); // parameters const unsigned HIDDEN_SIZE = 8; const unsigned ITERATIONS = 30; Model m; SimpleSGDTrainer sgd(&m); //MomentumSGDTrainer sgd(&m); Parameters& p_a = *m.add_parameters({1}); Parameters& p_b = *m.add_parameters({HIDDEN_SIZE}); Parameters& p_W = *m.add_parameters({HIDDEN_SIZE, 2}); Parameters& p_V = *m.add_parameters({1, HIDDEN_SIZE}); // build the graph Hypergraph hg; // get symbolic variables corresponding to parameters VariableIndex i_b = hg.add_parameter(&p_b); VariableIndex i_a = hg.add_parameter(&p_a); VariableIndex i_W = hg.add_parameter(&p_W); VariableIndex i_V = hg.add_parameter(&p_V); vector<float> x_values(2); // set x_values to change the inputs to the network VariableIndex i_x = hg.add_input({2}, &x_values); cnn::real y_value; // set y_value to change the target output VariableIndex i_y = hg.add_input(&y_value); // two options: MatrixMultiply and Sum, or Multilinear // these are identical, but Multilinear may be slightly more efficient #if 0 VariableIndex i_f = hg.add_function<MatrixMultiply>({i_W, i_x}); VariableIndex i_g = hg.add_function<Sum>({i_f, i_b}); #else VariableIndex i_g = hg.add_function<Multilinear>({i_b, i_W, i_x}); #endif VariableIndex i_h = hg.add_function<Tanh>({i_g}); #if 0 VariableIndex i_p = hg.add_function<MatrixMultiply>({i_V, i_h}); VariableIndex i_y_pred = hg.add_function<Sum>({i_p, i_a}); #else VariableIndex i_y_pred = hg.add_function<Multilinear>({i_a, i_V, i_h}); #endif hg.add_function<SquaredEuclideanDistance>({i_y_pred, i_y}); hg.PrintGraphviz(); if (argc == 2) { ifstream in(argv[1]); boost::archive::text_iarchive ia(in); ia >> m; } // train the parameters for (unsigned iter = 0; iter < ITERATIONS; ++iter) { double loss = 0; for (unsigned mi = 0; mi < 4; ++mi) { bool x1 = mi % 2; bool x2 = (mi / 2) % 2; x_values[0] = x1 ? 1 : -1; x_values[1] = x2 ? 1 : -1; y_value = (x1 != x2) ? 1 : -1; loss += as_scalar(hg.forward()); hg.backward(); sgd.update(1.0); } sgd.update_epoch(); loss /= 4; cerr << "E = " << loss << endl; } boost::archive::text_oarchive oa(cout); oa << m; } <|endoftext|>
<commit_before>// $Id$ AliAnalysisTaskSE* AddTaskJetPreparation( const char* dataType = "ESD", const char* periodstr = "LHC11h", const char* usedTracks = "PicoTracks", const char* usedMCParticles = "MCParticlesSelected", const char* usedClusters = "CaloClusters", const char* outClusName = "CaloClustersCorr", const Double_t hadcorr = 2.0, const Double_t Eexcl = 0.00, const Double_t phiMatch = 0.03, const Double_t etaMatch = 0.015, const Double_t minPtEt = 0.15, const UInt_t pSel = AliVEvent::kAny, const Bool_t trackclus = kTRUE, const Bool_t doHistos = kFALSE, const Bool_t makePicoTracks = kTRUE, const Bool_t isEmcalTrain = kFALSE ) { // Add task macros for all jet related helper tasks. AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskJetPreparation","No analysis manager found."); return 0; } // Set trackcuts according to period. Every period used should be definied here TString period(periodstr); TString clusterColName(usedClusters); TString particleColName(usedMCParticles); TString dType(dataType); if ((dType == "AOD") && (clusterColName == "CaloClusters")) clusterColName = "caloClusters"; if (makePicoTracks && (dType == "ESD" || dType == "AOD") ) { TString inputTracks = "tracks"; if (dType == "ESD") { inputTracks = "HybridTracks"; TString trackCuts(Form("Hybrid_%s", period.Data())); // Hybrid tracks maker for ESD gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalEsdTpcTrack.C"); AliEmcalEsdTpcTrackTask *hybTask = AddTaskEmcalEsdTpcTrack(inputTracks.Data(),trackCuts.Data()); hybTask->SelectCollisionCandidates(pSel); // Track propagator to extend track to the TPC boundaries gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalTrackPropagator.C"); AliEmcalTrackPropagatorTask *propTask = AddTaskEmcalTrackPropagator(inputTracks.Data()); propTask->SelectCollisionCandidates(pSel); } // Produce PicoTracks gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalPicoTrackMaker.C"); AliEmcalPicoTrackMaker *pTrackTask = AddTaskEmcalPicoTrackMaker("PicoTracks", inputTracks.Data(), period.Data()); pTrackTask->SelectCollisionCandidates(pSel); } // Produce particles used for hadronic correction gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalParticleMaker.C"); AliEmcalParticleMaker *emcalParts = AddTaskEmcalParticleMaker(usedTracks,clusterColName.Data(),"EmcalTracks","EmcalClusters"); emcalParts->SelectCollisionCandidates(pSel); // Relate tracks and clusters gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalClusTrackMatcher.C"); AliEmcalClusTrackMatcherTask *emcalClus = AddTaskEmcalClusTrackMatcher("EmcalTracks","EmcalClusters",0.1); emcalClus->SelectCollisionCandidates(pSel); if (isEmcalTrain) RequestMemory(emcalClus,100*1024); gROOT->LoadMacro("$ALICE_ROOT/PWGJE/EMCALJetTasks/macros/AddTaskHadCorr.C"); AliHadCorrTask *hCorr = AddTaskHadCorr("EmcalTracks","EmcalClusters",outClusName,hadcorr,minPtEt,phiMatch,etaMatch,Eexcl,trackclus,doHistos); hCorr->SelectCollisionCandidates(pSel); if (isEmcalTrain) { if (doHistos) RequestMemory(hCorr,250*1024); } // Produce MC particles if(particleColName != "") { gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskMCTrackSelector.C"); AliEmcalMCTrackSelector *mcPartTask = AddTaskMCTrackSelector(particleColName.Data(), kFALSE, kFALSE); mcPartTask->SelectCollisionCandidates(pSel); } // Return one task that represents the jet preparation on LEGO trains return emcalParts; } <commit_msg>more mem (Megan)<commit_after>// $Id$ AliAnalysisTaskSE* AddTaskJetPreparation( const char* dataType = "ESD", const char* periodstr = "LHC11h", const char* usedTracks = "PicoTracks", const char* usedMCParticles = "MCParticlesSelected", const char* usedClusters = "CaloClusters", const char* outClusName = "CaloClustersCorr", const Double_t hadcorr = 2.0, const Double_t Eexcl = 0.00, const Double_t phiMatch = 0.03, const Double_t etaMatch = 0.015, const Double_t minPtEt = 0.15, const UInt_t pSel = AliVEvent::kAny, const Bool_t trackclus = kTRUE, const Bool_t doHistos = kFALSE, const Bool_t makePicoTracks = kTRUE, const Bool_t isEmcalTrain = kFALSE ) { // Add task macros for all jet related helper tasks. AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskJetPreparation","No analysis manager found."); return 0; } // Set trackcuts according to period. Every period used should be definied here TString period(periodstr); TString clusterColName(usedClusters); TString particleColName(usedMCParticles); TString dType(dataType); if ((dType == "AOD") && (clusterColName == "CaloClusters")) clusterColName = "caloClusters"; if (makePicoTracks && (dType == "ESD" || dType == "AOD") ) { TString inputTracks = "tracks"; if (dType == "ESD") { inputTracks = "HybridTracks"; TString trackCuts(Form("Hybrid_%s", period.Data())); // Hybrid tracks maker for ESD gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalEsdTpcTrack.C"); AliEmcalEsdTpcTrackTask *hybTask = AddTaskEmcalEsdTpcTrack(inputTracks.Data(),trackCuts.Data()); hybTask->SelectCollisionCandidates(pSel); // Track propagator to extend track to the TPC boundaries gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalTrackPropagator.C"); AliEmcalTrackPropagatorTask *propTask = AddTaskEmcalTrackPropagator(inputTracks.Data()); propTask->SelectCollisionCandidates(pSel); } // Produce PicoTracks gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalPicoTrackMaker.C"); AliEmcalPicoTrackMaker *pTrackTask = AddTaskEmcalPicoTrackMaker("PicoTracks", inputTracks.Data(), period.Data()); pTrackTask->SelectCollisionCandidates(pSel); } // Produce particles used for hadronic correction gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalParticleMaker.C"); AliEmcalParticleMaker *emcalParts = AddTaskEmcalParticleMaker(usedTracks,clusterColName.Data(),"EmcalTracks","EmcalClusters"); emcalParts->SelectCollisionCandidates(pSel); // Relate tracks and clusters gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalClusTrackMatcher.C"); AliEmcalClusTrackMatcherTask *emcalClus = AddTaskEmcalClusTrackMatcher("EmcalTracks","EmcalClusters",0.1); emcalClus->SelectCollisionCandidates(pSel); if (isEmcalTrain) RequestMemory(emcalClus,100*1024); gROOT->LoadMacro("$ALICE_ROOT/PWGJE/EMCALJetTasks/macros/AddTaskHadCorr.C"); AliHadCorrTask *hCorr = AddTaskHadCorr("EmcalTracks","EmcalClusters",outClusName,hadcorr,minPtEt,phiMatch,etaMatch,Eexcl,trackclus,doHistos); hCorr->SelectCollisionCandidates(pSel); if (isEmcalTrain) { if (doHistos) RequestMemory(hCorr,500*1024); } // Produce MC particles if(particleColName != "") { gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskMCTrackSelector.C"); AliEmcalMCTrackSelector *mcPartTask = AddTaskMCTrackSelector(particleColName.Data(), kFALSE, kFALSE); mcPartTask->SelectCollisionCandidates(pSel); } // Return one task that represents the jet preparation on LEGO trains return emcalParts; } <|endoftext|>
<commit_before>#include<iostream> #include <cstdlib> #include <cstdio> #include <array> #include <utility> #include <boost/test/unit_test.hpp> using RawField = std::array<std::array<char, 32>, 32>; using RawStone = std::array<std::array<char, 8>, 8>; constexpr int ROTATE_90 = 1, ROTATE_180 = 2, ROTATE_270 = 4, REVERSED = 8; class Field { private: int score = 0; public: RawField raw = {}; int Score() const { return score; } bool TryPutStone(int stone_number, int base_x, int base_y, int manipulate_info); }; class Stone { public: RawStone raw = {}; }; Field max_score_field; Stone reserved_stones[256]; int number_of_stone = 0; void Parse(Field* f) { for (int i = 0; i < 32; ++i) { fread(f->raw[i].data(), sizeof(char[32]), 1, stdin); getchar(); //CR getchar(); //LF } scanf("\n%d\n", &number_of_stone); for (int i = 0; i < number_of_stone; ++i) { for (int j = 0; j < 8; ++j) { fread(reserved_stones[i].raw[j].data(), sizeof(char[8]), 1, stdin); getchar(); //CR getchar(); //LF } getchar(); //CR getchar(); //LF } } void DumpField(const Field& f) { for (int i = 0; i < 32; ++i) { for (int j = 0; j < 32; ++j) { putc(f.raw[i][j], stdout); } puts(""); } } void Solve(Field f, const int look_nth_stone) { if (look_nth_stone > number_of_stone) { if (f.Score() > max_score_field.Score()) { max_score_field = f; } return; } Solve(f, look_nth_stone + 1); Field backup = f; for (int x = -7; x < 32; ++x) { for (int y = -7; y < 32; ++y) { if (f.TryPutStone(look_nth_stone, x, y, 0)) { Solve(f, look_nth_stone+1); f = backup; } } } } void DumpStones() { for (int i = 0; i < number_of_stone; ++i) { for (int j = 0; j < 8; ++j) { for (int k = 0; k < 8; ++k) { putc(reserved_stones[i].raw[j][k], stdout); } puts(""); } puts(""); } } int main() { Field reserved_field; // get_problemfile(); Parse(&reserved_field); Solve(reserved_field, 0); DumpField(max_score_field); // solve(); // submit_answer(); return 0; } RawStone StoneRotate(RawStone& stone, int manipulate_info) { RawStone rotated; switch (manipulate_info) { case ROTATE_90: for (int y = 0; y < 8; ++y) { for (int x = 0; x < 8; ++x){ rotated[y][x] = stone[x][7-y]; } } return rotated; case ROTATE_180: return StoneRotate(std::move(StoneRotate(stone, ROTATE_90)), ROTATE_90); case ROTATE_270: return StoneRotate(std::move(StoneRotate(stone, ROTATE_180)), ROTATE_90); case REVERSED: for (int y = 0; y < 8; ++y) { for (int x = 0; x < 8; ++x) { rotated[y][x] = stone[y][7-x]; } } return rotated; case REVERSED | ROTATE_90: return StoneRotate(std::move(StoneRotate(stone, ROTATE_90), REVERSED); case REVERSED | ROTATE_180: return StoneRotate(std::move(StoneRotate(stone, ROTATE_180), REVERSED); case REVERSED | ROTATE_270: return StoneRotate(std::move(StoneRotate(stone, ROTATE_270), REVERSED); } return stone; } bool Field::TryPutStone(int stone_number, int base_x, int base_y, int manipulate_info) { // ๆ›ธใๆ›ใˆใ‚‹ใฎใงใ€ใ‚‚ใฉใ›ใ‚‹ใ‚ˆใ†ใซใ—ใฆใŠใ RawField backup_field = raw; int backup_score = score; RawStone& sraw = reserved_stones[stone_number].raw; for (int x = 0; x < 8; ++x) { for (int y = 0; y < 8; ++y) { if (y + base_y < 0 || y + base_y >= 32 || x + base_x < 0 || x + base_x >= 32) { continue; } if (sraw[y][x] == '1') { if(backup_score != 0 && raw[y + base_y][x + base_x] == '1') { //score = 1ใ€ใคใพใ‚Šๆœ€ๅˆใซ็ฝฎใ็Ÿณใชใ‚‰ๅˆคๅฎšใ—ใชใ„ raw = backup_field; score = backup_score; return false; } raw[y + base_y][x + base_x] = '1'; ++score; } } } return true; } // BOOST_AUTO_TEST_CASE(StoneRotate_Test) { RawStone rawstone = { "11111111", "00000000", "00000000", "00000000", "00000000", "00000000", "00000000", "00000000" }; RawStone rotated_90 = { "00000001", "00000001", "00000001", "00000001", "00000001", "00000001", "00000001", "00000001" }; RawStone rotated_by_f = std::move(StoneRotate(rawstone)); BOOST_CHECK_EQUAL(rotated_90, rotated_by_f); } <commit_msg>modified rotate algorithm<commit_after>#include<iostream> #include <cstdlib> #include <cstdio> #include <array> #include <utility> #include <cassert> using RawField = std::array<std::array<char, 32>, 32>; using RawStone = std::array<std::array<char, 8>, 8>; constexpr int ROTATE_90 = 1, ROTATE_180 = 2, ROTATE_270 = 4, REVERSE = 8; class Field { private: int score = 0; public: RawField raw = {}; int Score() const { return score; } bool TryPutStone(int stone_number, int base_x, int base_y, int manipulate_info); }; class Stone { public: RawStone raw = {}; }; Field max_score_field; Stone reserved_stones[256]; int number_of_stone = 0; void Parse(Field* f) { for (int i = 0; i < 32; ++i) { fread(f->raw[i].data(), sizeof(char[32]), 1, stdin); getchar(); //CR getchar(); //LF } scanf("\n%d\n", &number_of_stone); for (int i = 0; i < number_of_stone; ++i) { for (int j = 0; j < 8; ++j) { fread(reserved_stones[i].raw[j].data(), sizeof(char[8]), 1, stdin); getchar(); //CR getchar(); //LF } getchar(); //CR getchar(); //LF } } void DumpField(const Field& f) { for (int i = 0; i < 32; ++i) { for (int j = 0; j < 32; ++j) { putc(f.raw[i][j], stdout); } puts(""); } } void Solve(Field f, const int look_nth_stone) { if (look_nth_stone > number_of_stone) { if (f.Score() > max_score_field.Score()) { max_score_field = f; } return; } Solve(f, look_nth_stone + 1); Field backup = f; for (int x = -7; x < 32; ++x) { for (int y = -7; y < 32; ++y) { if (f.TryPutStone(look_nth_stone, x, y, 0)) { Solve(f, look_nth_stone+1); f = backup; } } } } void DumpStones() { for (int i = 0; i < number_of_stone; ++i) { for (int j = 0; j < 8; ++j) { for (int k = 0; k < 8; ++k) { putc(reserved_stones[i].raw[j][k], stdout); } puts(""); } puts(""); } } void test(); int main() { test(); Field reserved_field; // get_problemfile(); Parse(&reserved_field); Solve(reserved_field, 0); DumpField(max_score_field); // solve(); // submit_answer(); return 0; } RawStone StoneRotate(RawStone stone, int manipulate_info) { RawStone rotated; switch (manipulate_info) { case ROTATE_90: for (int a = 0; a < 8; ++a) { for (int b = 0; b < 8; ++b) { rotated[b][7-a] = stone[a][b]; } } return rotated; case ROTATE_180: return StoneRotate(std::move(StoneRotate(std::move(stone), ROTATE_90)), ROTATE_90); case ROTATE_270: return StoneRotate(std::move(StoneRotate(std::move(stone), ROTATE_180)), ROTATE_90); case REVERSE: for (int y = 0; y < 8; ++y) { for (int x = 0; x < 8; ++x) { rotated[y][x] = stone[y][7-x]; } } return rotated; case REVERSE | ROTATE_90: return StoneRotate(std::move(StoneRotate(std::move(stone), ROTATE_90)), REVERSE); case REVERSE | ROTATE_180: return StoneRotate(std::move(StoneRotate(std::move(stone), ROTATE_180)), REVERSE); case REVERSE | ROTATE_270: return StoneRotate(std::move(StoneRotate(std::move(stone), ROTATE_270)), REVERSE); } return stone; } bool Field::TryPutStone(int stone_number, int base_x, int base_y, int manipulate_info) { // ๆ›ธใๆ›ใˆใ‚‹ใฎใงใ€ใ‚‚ใฉใ›ใ‚‹ใ‚ˆใ†ใซใ—ใฆใŠใ RawField backup_field = raw; int backup_score = score; RawStone& sraw = reserved_stones[stone_number].raw; for (int x = 0; x < 8; ++x) { for (int y = 0; y < 8; ++y) { if (y + base_y < 0 || y + base_y >= 32 || x + base_x < 0 || x + base_x >= 32) { continue; } if (sraw[y][x] == '1') { if(backup_score != 0 && raw[y + base_y][x + base_x] == '1') { //score = 1ใ€ใคใพใ‚Šๆœ€ๅˆใซ็ฝฎใ็Ÿณใชใ‚‰ๅˆคๅฎšใ—ใชใ„ raw = backup_field; score = backup_score; return false; } raw[y + base_y][x + base_x] = '1'; ++score; } } } return true; } // void test() { RawStone rawstone; for (int x = 0; x < 8; ++x) { rawstone[0][x] = '1'; } for (int y = 1; y < 8; ++y) { for (int x = 0; x < 8; ++x) { rawstone[y][x] = '0'; } } RawStone rotated_90; for (int y = 0; y < 8; ++y) { rotated_90[y][7] = '1'; } for (int y = 0; y < 8; ++y) { for (int x = 0; x < 7; ++x) { rotated_90[y][x] = '0'; } } RawStone rotated_by_f = std::move(StoneRotate(rawstone, ROTATE_270|REVERSE)); assert(rotated_by_f == rotated_90); } <|endoftext|>
<commit_before>#include "from_json.h" #include <unordered_map> #include <stack> #include <asdf_multiplat/utilities/utilities.h> using namespace asdf; using namespace asdf::util; namespace tired_of_build_issues { std::string read_text_file(std::string const& filepath) { //if(!is_file(filepath)) //{ // //throw file_open_exception(filepath); // EXPLODE("C'est une probleme"); //} std::string outputstring; std::ifstream ifs(filepath, std::ifstream::in); ifs.exceptions( std::ios::failbit ); // ASSERT(ifs.good(), "Error loading text file %s", filepath.c_str()); if(!ifs.good()) { //throw file_open_exception(filepath); EXPLODE("C'est une probleme"); } ifs.seekg(0, std::ios::end); //seek to the end to get the size the output string should be outputstring.reserve(size_t(ifs.tellg())); //reserve necessary memory up front ifs.seekg(0, std::ios::beg); //seek back to the start outputstring.assign((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); ifs.close(); return outputstring; } } // custom hash function for std::path so that I can use it as // a key in unordered_map namespace std { template<> struct hash<stdfs::path> { size_t operator()(const stdfs::path &p) const { return std::hash<std::string>()(canonical(p)); } }; } namespace plantgen { // global stack used for resolving relative filepaths // when including other json files as node properties / values // I should probably devise a better method of doing this, since // I don't think this will handle more than one level of inclusion // if the JSON files are not all in the same directory //FIXME make this not global std::stack<stdfs::path> include_dir_stack; std::unordered_map<stdfs::path, pregen_node_t> include_cache; bool str_eq(char const* a, char const* b) { return strcmp(a, b) == 0; } std::vector<std::string> value_string_list_from_json_array(cJSON* json_array) { ASSERT(json_array, ""); ASSERT(json_array->type == cJSON_Array, "json_array is not actually a JSON array"); std::vector<std::string> values; cJSON* j = json_array->child; while(j) { ASSERT(j->type == cJSON_String, "Expected a JSON string"); values.emplace_back(j->valuestring); j = j->next; } return values; } multi_value_t multi_value_from_json(cJSON* json) { ASSERT(str_eq(json->child->string, "Multi"), "Expected a \"Multi\" json_obj"); ASSERT(json->child->type == cJSON_Number, "JSON Value of \"Multi\" should be an integer"); multi_value_t v; v.num_to_pick = json->child->valueint; v.values = std::move(value_string_list_from_json_array(json->child->next)); return v; } range_value_t range_value_from_json(cJSON* json) { ASSERT(str_eq(json->string, "Range"), "Expected a \"Range\" json_obj"); return value_string_list_from_json_array(json); } weighted_value_t value_type_from_json(cJSON* json) { if(json->type == cJSON_String) { return std::string(json->valuestring); } else if(!json->child) { EXPLODE("invalid value object %s", json->string); return null_value_t(); } else if(str_eq(json->child->string, "Multi")) { return multi_value_from_json(json); } else if(str_eq(json->child->string, "Range")) { return range_value_from_json(json->child); } else { EXPLODE("unrecognized value object %s", json->child->string); return weighted_value_t(null_value_t()); } } pregen_node_t node_from_json(cJSON* json_node) { pregen_node_t node; node.name = std::string(CJSON_STR(json_node, Name)); cJSON* cur_child = json_node->child; while(cur_child) { if(str_eq(cur_child->string, "Properties")) { cJSON* property_json = cur_child->child; while(property_json) { node.add_child(node_from_json(property_json)); property_json = property_json->next; } } else if(str_eq(cur_child->string, "Values")) { cJSON* value_json = cur_child->child; while(value_json) { // if the value is a node, load it differently // since we can't return a node as part of the variant //if the value is an object starting with a child named "Name", it's a node if(value_json->type == cJSON_Object && value_json->child && str_eq(value_json->child->string, "Name")) { node.value_nodes.push_back(std::move(node_from_json(value_json))); } else { node.values.push_back(std::move(value_type_from_json(value_json))); } value_json = value_json->next; } } else if(str_eq(cur_child->string, "Include")) { ASSERT(cur_child->type == cJSON_String, "Include filepath must be a string"); stdfs::path relpath(cur_child->valuestring); auto parent_path = include_dir_stack.top().parent_path(); stdfs::path fullpath = parent_path / relpath; try{ auto included_node = node_from_json(fullpath); if(included_node.name == node.name) { node.merge_with(std::move(included_node)); } else { node.add_child(std::move(included_node)); } } catch(file_not_found_exception const&) { throw include_exception{include_dir_stack.top(), fullpath}; } } else if(str_eq(cur_child->string, "Weight")) { if(cur_child->type != cJSON_Number) throw json_type_exception(include_dir_stack.top(), cur_child, cJSON_Number); node.weight = cur_child->valueint; } else { // LOG("Unrecognized tag '%s' in node '%s'", cur_child->string, json_node->string); } cur_child = cur_child->next; } return node; } pregen_node_t node_from_json(stdfs::path const& filepath) { if(!stdfs::is_regular_file(filepath)) throw file_not_found_exception{filepath}; auto canonical_path = stdfs::canonical(filepath); auto cached_node_entry = include_cache.find(canonical_path); if(cached_node_entry != include_cache.end()) { return cached_node_entry->second; } else { //std::string json_str = asdf::util::read_text_file(filepath); std::string json_str = tired_of_build_issues::read_text_file(canonical_path.string()); cJSON* json_root = cJSON_Parse(json_str.c_str()); if(!json_root) { throw json_parse_exception(filepath, cJSON_GetErrorPtr()); } include_dir_stack.push(canonical_path); auto node = node_from_json(json_root); cJSON_Delete(json_root); include_dir_stack.pop(); include_cache.insert({canonical_path, node}); return node; } } generated_node_t generate_node_from_json(stdfs::path const& filepath) { auto node = node_from_json(filepath); return generate_node(node); } }<commit_msg>msvc fix<commit_after>#include "from_json.h" #include <unordered_map> #include <stack> #include <asdf_multiplat/utilities/utilities.h> using namespace asdf; using namespace asdf::util; namespace tired_of_build_issues { std::string read_text_file(std::string const& filepath) { //if(!is_file(filepath)) //{ // //throw file_open_exception(filepath); // EXPLODE("C'est une probleme"); //} std::string outputstring; std::ifstream ifs(filepath, std::ifstream::in); ifs.exceptions( std::ios::failbit ); // ASSERT(ifs.good(), "Error loading text file %s", filepath.c_str()); if(!ifs.good()) { //throw file_open_exception(filepath); EXPLODE("C'est une probleme"); } ifs.seekg(0, std::ios::end); //seek to the end to get the size the output string should be outputstring.reserve(size_t(ifs.tellg())); //reserve necessary memory up front ifs.seekg(0, std::ios::beg); //seek back to the start outputstring.assign((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); ifs.close(); return outputstring; } } // custom hash function for std::path so that I can use it as // a key in unordered_map namespace std { template<> struct hash<stdfs::path> { size_t operator()(const stdfs::path &p) const { return std::hash<std::string>()(canonical(p).string()); } }; } namespace plantgen { // global stack used for resolving relative filepaths // when including other json files as node properties / values // I should probably devise a better method of doing this, since // I don't think this will handle more than one level of inclusion // if the JSON files are not all in the same directory //FIXME make this not global std::stack<stdfs::path> include_dir_stack; std::unordered_map<stdfs::path, pregen_node_t> include_cache; bool str_eq(char const* a, char const* b) { return strcmp(a, b) == 0; } std::vector<std::string> value_string_list_from_json_array(cJSON* json_array) { ASSERT(json_array, ""); ASSERT(json_array->type == cJSON_Array, "json_array is not actually a JSON array"); std::vector<std::string> values; cJSON* j = json_array->child; while(j) { ASSERT(j->type == cJSON_String, "Expected a JSON string"); values.emplace_back(j->valuestring); j = j->next; } return values; } multi_value_t multi_value_from_json(cJSON* json) { ASSERT(str_eq(json->child->string, "Multi"), "Expected a \"Multi\" json_obj"); ASSERT(json->child->type == cJSON_Number, "JSON Value of \"Multi\" should be an integer"); multi_value_t v; v.num_to_pick = json->child->valueint; v.values = std::move(value_string_list_from_json_array(json->child->next)); return v; } range_value_t range_value_from_json(cJSON* json) { ASSERT(str_eq(json->string, "Range"), "Expected a \"Range\" json_obj"); return value_string_list_from_json_array(json); } weighted_value_t value_type_from_json(cJSON* json) { if(json->type == cJSON_String) { return std::string(json->valuestring); } else if(!json->child) { EXPLODE("invalid value object %s", json->string); return null_value_t(); } else if(str_eq(json->child->string, "Multi")) { return multi_value_from_json(json); } else if(str_eq(json->child->string, "Range")) { return range_value_from_json(json->child); } else { EXPLODE("unrecognized value object %s", json->child->string); return weighted_value_t(null_value_t()); } } pregen_node_t node_from_json(cJSON* json_node) { pregen_node_t node; node.name = std::string(CJSON_STR(json_node, Name)); cJSON* cur_child = json_node->child; while(cur_child) { if(str_eq(cur_child->string, "Properties")) { cJSON* property_json = cur_child->child; while(property_json) { node.add_child(node_from_json(property_json)); property_json = property_json->next; } } else if(str_eq(cur_child->string, "Values")) { cJSON* value_json = cur_child->child; while(value_json) { // if the value is a node, load it differently // since we can't return a node as part of the variant //if the value is an object starting with a child named "Name", it's a node if(value_json->type == cJSON_Object && value_json->child && str_eq(value_json->child->string, "Name")) { node.value_nodes.push_back(std::move(node_from_json(value_json))); } else { node.values.push_back(std::move(value_type_from_json(value_json))); } value_json = value_json->next; } } else if(str_eq(cur_child->string, "Include")) { ASSERT(cur_child->type == cJSON_String, "Include filepath must be a string"); stdfs::path relpath(cur_child->valuestring); auto parent_path = include_dir_stack.top().parent_path(); stdfs::path fullpath = parent_path / relpath; try{ auto included_node = node_from_json(fullpath); if(included_node.name == node.name) { node.merge_with(std::move(included_node)); } else { node.add_child(std::move(included_node)); } } catch(file_not_found_exception const&) { throw include_exception{include_dir_stack.top(), fullpath}; } } else if(str_eq(cur_child->string, "Weight")) { if(cur_child->type != cJSON_Number) throw json_type_exception(include_dir_stack.top(), cur_child, cJSON_Number); node.weight = cur_child->valueint; } else { // LOG("Unrecognized tag '%s' in node '%s'", cur_child->string, json_node->string); } cur_child = cur_child->next; } return node; } pregen_node_t node_from_json(stdfs::path const& filepath) { if(!stdfs::is_regular_file(filepath)) throw file_not_found_exception{filepath}; auto canonical_path = stdfs::canonical(filepath); auto cached_node_entry = include_cache.find(canonical_path); if(cached_node_entry != include_cache.end()) { return cached_node_entry->second; } else { //std::string json_str = asdf::util::read_text_file(filepath); std::string json_str = tired_of_build_issues::read_text_file(canonical_path.string()); cJSON* json_root = cJSON_Parse(json_str.c_str()); if(!json_root) { throw json_parse_exception(filepath, cJSON_GetErrorPtr()); } include_dir_stack.push(canonical_path); auto node = node_from_json(json_root); cJSON_Delete(json_root); include_dir_stack.pop(); include_cache.insert({canonical_path, node}); return node; } } generated_node_t generate_node_from_json(stdfs::path const& filepath) { auto node = node_from_json(filepath); return generate_node(node); } }<|endoftext|>
<commit_before>/* * Copyright (c) 2002-2005 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. */ #ifndef __SYSTEM_HH__ #define __SYSTEM_HH__ #include <string> #include <vector> #include "base/statistics.hh" #include "base/loader/symtab.hh" #include "cpu/pc_event.hh" #include "kern/system_events.hh" #include "sim/sim_object.hh" class BaseCPU; class ExecContext; class GDBListener; class MemoryController; class ObjectFile; class PhysicalMemory; class Platform; class RemoteGDB; namespace Kernel { class Binning; } class System : public SimObject { public: MemoryController *memctrl; PhysicalMemory *physmem; Platform *platform; PCEventQueue pcEventQueue; uint64_t init_param; std::vector<ExecContext *> execContexts; int numcpus; int getNumCPUs() { if (numcpus != execContexts.size()) panic("cpu array not fully populated!"); return numcpus; } /** kernel symbol table */ SymbolTable *kernelSymtab; /** console symbol table */ SymbolTable *consoleSymtab; /** pal symbol table */ SymbolTable *palSymtab; /** Object pointer for the kernel code */ ObjectFile *kernel; /** Object pointer for the console code */ ObjectFile *console; /** Object pointer for the PAL code */ ObjectFile *pal; /** Begining of kernel code */ Addr kernelStart; /** End of kernel code */ Addr kernelEnd; /** Entry point in the kernel to start at */ Addr kernelEntry; Kernel::Binning *kernelBinning; #ifdef DEBUG /** Event to halt the simulator if the console calls panic() */ BreakPCEvent *consolePanicEvent; #endif protected: /** * Fix up an address used to match PCs for hooking simulator * events on to target function executions. See comment in * system.cc for details. */ Addr fixFuncEventAddr(Addr addr); /** * Add a function-based event to the given function, to be looked * up in the specified symbol table. */ template <class T> T *System::addFuncEvent(SymbolTable *symtab, const char *lbl) { Addr addr; if (symtab->findAddress(lbl, addr)) { T *ev = new T(&pcEventQueue, lbl, fixFuncEventAddr(addr)); return ev; } return NULL; } /** Add a function-based event to kernel code. */ template <class T> T *System::addKernelFuncEvent(const char *lbl) { return addFuncEvent<T>(kernelSymtab, lbl); } /** Add a function-based event to PALcode. */ template <class T> T *System::addPalFuncEvent(const char *lbl) { return addFuncEvent<T>(palSymtab, lbl); } /** Add a function-based event to the console code. */ template <class T> T *System::addConsoleFuncEvent(const char *lbl) { return addFuncEvent<T>(consoleSymtab, lbl); } public: std::vector<RemoteGDB *> remoteGDB; std::vector<GDBListener *> gdbListen; bool breakpoint(); public: struct Params { std::string name; Tick boot_cpu_frequency; MemoryController *memctrl; PhysicalMemory *physmem; uint64_t init_param; bool bin; std::vector<std::string> binned_fns; bool bin_int; std::string kernel_path; std::string console_path; std::string palcode; std::string boot_osflags; std::string readfile; uint64_t system_type; uint64_t system_rev; }; Params *params; System(Params *p); ~System(); void startup(); public: /** * Set the m5AlphaAccess pointer in the console */ void setAlphaAccess(Addr access); /** * Returns the addess the kernel starts at. * @return address the kernel starts at */ Addr getKernelStart() const { return kernelStart; } /** * Returns the addess the kernel ends at. * @return address the kernel ends at */ Addr getKernelEnd() const { return kernelEnd; } /** * Returns the addess the entry point to the kernel code. * @return entry point of the kernel code */ Addr getKernelEntry() const { return kernelEntry; } int registerExecContext(ExecContext *xc, int xcIndex); void replaceExecContext(ExecContext *xc, int xcIndex); void regStats(); void serialize(std::ostream &os); void unserialize(Checkpoint *cp, const std::string &section); public: //////////////////////////////////////////// // // STATIC GLOBAL SYSTEM LIST // //////////////////////////////////////////// static std::vector<System *> systemList; static int numSystemsRunning; static void printSystems(); }; #endif // __SYSTEM_HH__ <commit_msg>Fix for g++ 4 warning... not sure why this is just popping up now.<commit_after>/* * Copyright (c) 2002-2005 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. */ #ifndef __SYSTEM_HH__ #define __SYSTEM_HH__ #include <string> #include <vector> #include "base/statistics.hh" #include "base/loader/symtab.hh" #include "cpu/pc_event.hh" #include "kern/system_events.hh" #include "sim/sim_object.hh" class BaseCPU; class ExecContext; class GDBListener; class MemoryController; class ObjectFile; class PhysicalMemory; class Platform; class RemoteGDB; namespace Kernel { class Binning; } class System : public SimObject { public: MemoryController *memctrl; PhysicalMemory *physmem; Platform *platform; PCEventQueue pcEventQueue; uint64_t init_param; std::vector<ExecContext *> execContexts; int numcpus; int getNumCPUs() { if (numcpus != execContexts.size()) panic("cpu array not fully populated!"); return numcpus; } /** kernel symbol table */ SymbolTable *kernelSymtab; /** console symbol table */ SymbolTable *consoleSymtab; /** pal symbol table */ SymbolTable *palSymtab; /** Object pointer for the kernel code */ ObjectFile *kernel; /** Object pointer for the console code */ ObjectFile *console; /** Object pointer for the PAL code */ ObjectFile *pal; /** Begining of kernel code */ Addr kernelStart; /** End of kernel code */ Addr kernelEnd; /** Entry point in the kernel to start at */ Addr kernelEntry; Kernel::Binning *kernelBinning; #ifdef DEBUG /** Event to halt the simulator if the console calls panic() */ BreakPCEvent *consolePanicEvent; #endif protected: /** * Fix up an address used to match PCs for hooking simulator * events on to target function executions. See comment in * system.cc for details. */ Addr fixFuncEventAddr(Addr addr); /** * Add a function-based event to the given function, to be looked * up in the specified symbol table. */ template <class T> T *System::addFuncEvent(SymbolTable *symtab, const char *lbl) { Addr addr = 0; // initialize only to avoid compiler warning if (symtab->findAddress(lbl, addr)) { T *ev = new T(&pcEventQueue, lbl, fixFuncEventAddr(addr)); return ev; } return NULL; } /** Add a function-based event to kernel code. */ template <class T> T *System::addKernelFuncEvent(const char *lbl) { return addFuncEvent<T>(kernelSymtab, lbl); } /** Add a function-based event to PALcode. */ template <class T> T *System::addPalFuncEvent(const char *lbl) { return addFuncEvent<T>(palSymtab, lbl); } /** Add a function-based event to the console code. */ template <class T> T *System::addConsoleFuncEvent(const char *lbl) { return addFuncEvent<T>(consoleSymtab, lbl); } public: std::vector<RemoteGDB *> remoteGDB; std::vector<GDBListener *> gdbListen; bool breakpoint(); public: struct Params { std::string name; Tick boot_cpu_frequency; MemoryController *memctrl; PhysicalMemory *physmem; uint64_t init_param; bool bin; std::vector<std::string> binned_fns; bool bin_int; std::string kernel_path; std::string console_path; std::string palcode; std::string boot_osflags; std::string readfile; uint64_t system_type; uint64_t system_rev; }; Params *params; System(Params *p); ~System(); void startup(); public: /** * Set the m5AlphaAccess pointer in the console */ void setAlphaAccess(Addr access); /** * Returns the addess the kernel starts at. * @return address the kernel starts at */ Addr getKernelStart() const { return kernelStart; } /** * Returns the addess the kernel ends at. * @return address the kernel ends at */ Addr getKernelEnd() const { return kernelEnd; } /** * Returns the addess the entry point to the kernel code. * @return entry point of the kernel code */ Addr getKernelEntry() const { return kernelEntry; } int registerExecContext(ExecContext *xc, int xcIndex); void replaceExecContext(ExecContext *xc, int xcIndex); void regStats(); void serialize(std::ostream &os); void unserialize(Checkpoint *cp, const std::string &section); public: //////////////////////////////////////////// // // STATIC GLOBAL SYSTEM LIST // //////////////////////////////////////////// static std::vector<System *> systemList; static int numSystemsRunning; static void printSystems(); }; #endif // __SYSTEM_HH__ <|endoftext|>
<commit_before>/* Copyright (C) 2015 Yannick Mueller This file is part of longscroll-qt. longscroll-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. longscroll-qt 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with longscroll-qt. If not see <http://www.gnu.org/licenses/>. */ #include "mainwindow.h" #include "ui_mainwindow.h" #include "itemfactories.h" #include "valueeditdialog.h" #include <longscroll-qt/contentwidget.h> #include <longscroll-qt/contentwidgetitemfactory.h> #include <QScrollBar> #include <QMetaProperty> #include <QFileDialog> #include <QMessageBox> #include <QInputDialog> #include <QDebug> #include <algorithm> #include <random> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ContentWidget * cw = ui->longscroll->getContentWidget(); const QMetaObject * mo = cw->metaObject(); QStringList blacklist; blacklist << "dragEnabled" << "selectedItems" << "currentItem"; for (int i = mo->superClass()->propertyCount(), count = mo->propertyCount(); i < count; ++i) { QMetaProperty const & prop = mo->property(i); if (prop.userType() == QMetaType::UnknownType || !prop.isReadable() || !prop.isWritable() || blacklist.contains(prop.name())) continue; ui->menuProperties->addAction(QString())->setData(i); } demoGroup = new QActionGroup(ui->menuProperties); for (int i = 0; i < 5; ++i) { QAction * a = new QAction(tr("Demo %1").arg(i+1), demoGroup); a->setData(i); a->setCheckable(true); a->setChecked(i == 0); } ui->menuDemo->addActions(demoGroup->actions()); setDemoNumber(0); connect(ui->menuFile, &QMenu::aboutToShow, this, &MainWindow::updateFileMenu); connect(ui->menuProperties, &QMenu::aboutToShow, this, &MainWindow::updatePropertyMenu); connect(ui->menuProperties, &QMenu::triggered, this, &MainWindow::propertyMenuTriggered); connect(demoGroup, &QActionGroup::triggered, this, &MainWindow::demoMenuTriggered); } MainWindow::~MainWindow() { delete ui; } void MainWindow::setItemInfos(const QList<ContentItemInfo> & infos, int fixedSize, bool shuffle) { ContentWidget * cw = ui->longscroll->getContentWidget(); QList<ContentItemInfo> displayInfos = infos; if (fixedSize == -1) fixedSize = fixedInfoSize; if (fixedSize > 0) { qDebug() << "creating items ..."; displayInfos.clear(); for (int i = 0; i < fixedSize; ++i) displayInfos.append(infos.at(i % infos.count())); qDebug() << "created" << fixedSize << "items"; } if (shuffle) { std::random_device rd; std::mt19937 rng(rd()); std::shuffle(displayInfos.begin(), displayInfos.end(), rng); qDebug() << "shuffled"; } fixedInfoSize = fixedSize; itemInfos = infos; cw->setItemInfos(displayInfos); } void MainWindow::setFixedItemCount(int fixedSize) { setItemInfos(itemInfos, fixedSize); } void MainWindow::setDemoNumber(int demoNo) { ContentWidget * cw = ui->longscroll->getContentWidget(); ContentWidgetItemFactory * cwif = 0; switch (demoNo) { default: case 0: //Default Values cw->setRowHeight(200); cw->setItemWidth(0); cw->setStretchRows(true); cw->setStretchLastRow(false); cw->setScaleRows(false); cw->setAllowOverfill(true); cw->setNavigatorHeight(500); cwif = new ContentWidgetLoaderImageItemFactory(false); break; case 1: cw->setRowHeight(200); cw->setItemWidth(0); cw->setStretchRows(true); cw->setStretchLastRow(false); cw->setScaleRows(true); cw->setAllowOverfill(true); cw->setNavigatorHeight(500); cwif = new ContentWidgetLoaderImageItemFactory(false); break; case 2: cw->setRowHeight(100); cw->setItemWidth(100); cw->setStretchRows(false); cw->setStretchLastRow(false); cw->setScaleRows(false); cw->setAllowOverfill(false); cw->setNavigatorHeight(200); cwif = new ContentWidgetLoaderImageItemFactory(true); break; case 3: cw->setRowHeight(100); cw->setItemWidth(-1); cw->setStretchRows(true); cw->setStretchLastRow(true); cw->setScaleRows(false); cw->setAllowOverfill(false); cw->setNavigatorHeight(200); cwif = new ContentWidgetLoaderImageItemFactory(true); break; case 4: cw->setRowHeight(100); cw->setItemWidth(200); cw->setStretchRows(false); cw->setScaleRows(false); cw->setStretchLastRow(false); cw->setAllowOverfill(false); cw->setNavigatorHeight(200); cwif = new ContentWidgetImageInfoFactory(); break; } cw->setItemFactory(cwif); demoGroup->blockSignals(true); QAction * a = demoGroup->actions().value(demoNo); a->setChecked(a); demoGroup->blockSignals(false); } void MainWindow::loadDir(const QDir & dir, bool useCache) { if (!dir.exists()) return; QMap<QString, ContentItemInfo> cache, loadedCache; QFile cacheFile(dir.absoluteFilePath("images.cache")); if (cacheFile.exists()) { if (cacheFile.open(QIODevice::ReadOnly)) { QByteArray const & buffer = qUncompress(cacheFile.readAll()); cacheFile.close(); QDataStream ds(buffer); ds >> loadedCache; } else { qWarning() << "could not open cache file:" << cacheFile.fileName(); } } cache = loadedCache; qDebug() << "cached images:" << cache.size(); QStringList fileNamefilters; for (QString const & format : QImageReader::supportedImageFormats()) fileNamefilters.append(QString("*.%1").arg(format)); QImageReader ir; qDebug() << "loading file list for" << dir.absolutePath() << "..."; QFileInfoList const & files = dir.entryInfoList(fileNamefilters, QDir::Files | QDir::Readable); qDebug() << "loading images from" << dir.absolutePath() << "..."; for (QFileInfo const & file : files) { QString const & fileName = file.absoluteFilePath(); if (cache.contains(fileName)) continue; ir.setFileName(fileName); cache.insert(fileName, ContentItemInfo(fileName, ir.size())); } qDebug() << "checking file existence ..."; for (auto it = cache.begin(); it != cache.end(); ) { QFileInfo fi(it.key()); if (fi.exists()) ++it; else it = cache.erase(it); } if (useCache && cache != loadedCache) { qDebug() << "storing cache file ..."; QByteArray buffer; if (cacheFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) { QDataStream ds(&buffer, QIODevice::WriteOnly); ds << cache; cacheFile.write(qCompress(buffer, 9)); cacheFile.close(); } else { qWarning() << "Could not open" << cacheFile.fileName() << "for write."; } } qDebug() << "loaded" << cache.size() << "images"; qDebug() << "loading gui ..."; setItemInfos(cache.values(), fixedInfoSize); } void MainWindow::updateFileMenu() { ui->actionCount->setText(tr("Count = %1").arg(fixedInfoSize)); } void MainWindow::updatePropertyMenu() { ContentWidget * cw = ui->longscroll->getContentWidget(); const QMetaObject * mo = cw->metaObject(); for (QAction * a : ui->menuProperties->actions()) { QMetaProperty const & prop = mo->property(a->data().toInt()); QString const & name = prop.name(); int type = prop.userType(); QVariant const & value = prop.read(cw); QString const & displayName = QString("%1 = %2").arg(name, prop.read(cw).toString()); a->setText(displayName); switch (type) { case QMetaType::Bool: a->setCheckable(true); a->setChecked(value.toBool()); break; default: break; } } } void MainWindow::propertyMenuTriggered(QAction * action) { for (QAction * a : demoGroup->actions()) a->setChecked(false); ContentWidget * cw = ui->longscroll->getContentWidget(); const QMetaObject * mo = cw->metaObject(); QMetaProperty const & prop = mo->property(action->data().toInt()); switch (prop.userType()) { case QMetaType::Bool: prop.write(cw, action->isChecked()); break; default: ValueEditDialog ved(this); ved.setValue(prop.name(), prop.read(cw)); if (ved.exec() == QDialog::Accepted) prop.write(cw, ved.getValue()); break; } } void MainWindow::demoMenuTriggered(QAction * action) { setDemoNumber(action->data().toInt()); } void MainWindow::on_actionOpen_triggered() { if (fileDialog == 0) { fileDialog = new QFileDialog(this); fileDialog->setAcceptMode(QFileDialog::AcceptOpen); fileDialog->setFileMode(QFileDialog::Directory); fileDialog->setOption(QFileDialog::ShowDirsOnly, true); } if (fileDialog->exec() != QDialog::Accepted) return; QDir dir(fileDialog->selectedFiles().first()); dir.makeAbsolute(); QFileInfo cacheInfo(dir.filePath("images.cache")); qDebug() << cacheInfo.absoluteFilePath() << cacheInfo.exists() << cacheInfo.isFile() << cacheInfo.isWritable() << cacheInfo.permissions(); QFileInfo dirInfo(dir.absolutePath()); qDebug() << dirInfo.absoluteFilePath() << dirInfo.isWritable() << dirInfo.permissions(); bool useCache = ((!cacheInfo.exists() && QFileInfo(dir.absolutePath()).isWritable()) || (cacheInfo.isFile() && cacheInfo.isWritable())); if (useCache && QMessageBox::question(this, tr("Write Cache File?"), tr("Write a cache file?\nThis is useful if you open a directory with a large number of files more than once.")) != QMessageBox::Yes) useCache = false; loadDir(dir, useCache); } void MainWindow::on_actionCount_triggered() { bool ok; int val = QInputDialog::getInt(this, "Count", "Fixed number of images", fixedInfoSize, 0, std::numeric_limits<int>::max(), 1, &ok); if (ok) setFixedItemCount(val); } void MainWindow::on_actionShuffle_triggered() { setItemInfos(itemInfos, fixedInfoSize, true); } <commit_msg>Fixed demo 5<commit_after>/* Copyright (C) 2015 Yannick Mueller This file is part of longscroll-qt. longscroll-qt is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. longscroll-qt 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with longscroll-qt. If not see <http://www.gnu.org/licenses/>. */ #include "mainwindow.h" #include "ui_mainwindow.h" #include "itemfactories.h" #include "valueeditdialog.h" #include <longscroll-qt/contentwidget.h> #include <longscroll-qt/contentwidgetitemfactory.h> #include <QScrollBar> #include <QMetaProperty> #include <QFileDialog> #include <QMessageBox> #include <QInputDialog> #include <QDebug> #include <algorithm> #include <random> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ContentWidget * cw = ui->longscroll->getContentWidget(); const QMetaObject * mo = cw->metaObject(); QStringList blacklist; blacklist << "dragEnabled" << "selectedItems" << "currentItem"; for (int i = mo->superClass()->propertyCount(), count = mo->propertyCount(); i < count; ++i) { QMetaProperty const & prop = mo->property(i); if (prop.userType() == QMetaType::UnknownType || !prop.isReadable() || !prop.isWritable() || blacklist.contains(prop.name())) continue; ui->menuProperties->addAction(QString())->setData(i); } demoGroup = new QActionGroup(ui->menuProperties); for (int i = 0; i < 5; ++i) { QAction * a = new QAction(tr("Demo %1").arg(i+1), demoGroup); a->setData(i); a->setCheckable(true); a->setChecked(i == 0); } ui->menuDemo->addActions(demoGroup->actions()); setDemoNumber(0); connect(ui->menuFile, &QMenu::aboutToShow, this, &MainWindow::updateFileMenu); connect(ui->menuProperties, &QMenu::aboutToShow, this, &MainWindow::updatePropertyMenu); connect(ui->menuProperties, &QMenu::triggered, this, &MainWindow::propertyMenuTriggered); connect(demoGroup, &QActionGroup::triggered, this, &MainWindow::demoMenuTriggered); } MainWindow::~MainWindow() { delete ui; } void MainWindow::setItemInfos(const QList<ContentItemInfo> & infos, int fixedSize, bool shuffle) { ContentWidget * cw = ui->longscroll->getContentWidget(); QList<ContentItemInfo> displayInfos = infos; if (fixedSize == -1) fixedSize = fixedInfoSize; if (fixedSize > 0) { qDebug() << "creating items ..."; displayInfos.clear(); for (int i = 0; i < fixedSize; ++i) displayInfos.append(infos.at(i % infos.count())); qDebug() << "created" << fixedSize << "items"; } if (shuffle) { std::random_device rd; std::mt19937 rng(rd()); std::shuffle(displayInfos.begin(), displayInfos.end(), rng); qDebug() << "shuffled"; } fixedInfoSize = fixedSize; itemInfos = infos; cw->setItemInfos(displayInfos); } void MainWindow::setFixedItemCount(int fixedSize) { setItemInfos(itemInfos, fixedSize); } void MainWindow::setDemoNumber(int demoNo) { ContentWidget * cw = ui->longscroll->getContentWidget(); ContentWidgetItemFactory * cwif = 0; switch (demoNo) { default: case 0: //Default Values cw->setRowHeight(200); cw->setItemWidth(0); cw->setStretchRows(true); cw->setStretchLastRow(false); cw->setScaleRows(false); cw->setAllowOverfill(true); cw->setNavigatorHeight(500); cwif = new ContentWidgetLoaderImageItemFactory(false); break; case 1: cw->setRowHeight(200); cw->setItemWidth(0); cw->setStretchRows(true); cw->setStretchLastRow(false); cw->setScaleRows(true); cw->setAllowOverfill(true); cw->setNavigatorHeight(500); cwif = new ContentWidgetLoaderImageItemFactory(false); break; case 2: cw->setRowHeight(100); cw->setItemWidth(100); cw->setStretchRows(false); cw->setStretchLastRow(false); cw->setScaleRows(false); cw->setAllowOverfill(false); cw->setNavigatorHeight(200); cwif = new ContentWidgetLoaderImageItemFactory(true); break; case 3: cw->setRowHeight(100); cw->setItemWidth(-1); cw->setStretchRows(true); cw->setStretchLastRow(true); cw->setScaleRows(false); cw->setAllowOverfill(false); cw->setNavigatorHeight(200); cwif = new ContentWidgetLoaderImageItemFactory(true); break; case 4: cw->setRowHeight(100); cw->setItemWidth(400); cw->setStretchRows(false); cw->setScaleRows(false); cw->setStretchLastRow(false); cw->setAllowOverfill(false); cw->setNavigatorHeight(200); cwif = new ContentWidgetImageInfoFactory(); break; } cw->setItemFactory(cwif); demoGroup->blockSignals(true); QAction * a = demoGroup->actions().value(demoNo); a->setChecked(a); demoGroup->blockSignals(false); } void MainWindow::loadDir(const QDir & dir, bool useCache) { if (!dir.exists()) return; QMap<QString, ContentItemInfo> cache, loadedCache; QFile cacheFile(dir.absoluteFilePath("images.cache")); if (cacheFile.exists()) { if (cacheFile.open(QIODevice::ReadOnly)) { QByteArray const & buffer = qUncompress(cacheFile.readAll()); cacheFile.close(); QDataStream ds(buffer); ds >> loadedCache; } else { qWarning() << "could not open cache file:" << cacheFile.fileName(); } } cache = loadedCache; qDebug() << "cached images:" << cache.size(); QStringList fileNamefilters; for (QString const & format : QImageReader::supportedImageFormats()) fileNamefilters.append(QString("*.%1").arg(format)); QImageReader ir; qDebug() << "loading file list for" << dir.absolutePath() << "..."; QFileInfoList const & files = dir.entryInfoList(fileNamefilters, QDir::Files | QDir::Readable); qDebug() << "loading images from" << dir.absolutePath() << "..."; for (QFileInfo const & file : files) { QString const & fileName = file.absoluteFilePath(); if (cache.contains(fileName)) continue; ir.setFileName(fileName); cache.insert(fileName, ContentItemInfo(fileName, ir.size())); } qDebug() << "checking file existence ..."; for (auto it = cache.begin(); it != cache.end(); ) { QFileInfo fi(it.key()); if (fi.exists()) ++it; else it = cache.erase(it); } if (useCache && cache != loadedCache) { qDebug() << "storing cache file ..."; QByteArray buffer; if (cacheFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) { QDataStream ds(&buffer, QIODevice::WriteOnly); ds << cache; cacheFile.write(qCompress(buffer, 9)); cacheFile.close(); } else { qWarning() << "Could not open" << cacheFile.fileName() << "for write."; } } qDebug() << "loaded" << cache.size() << "images"; qDebug() << "loading gui ..."; setItemInfos(cache.values(), fixedInfoSize); } void MainWindow::updateFileMenu() { ui->actionCount->setText(tr("Count = %1").arg(fixedInfoSize)); } void MainWindow::updatePropertyMenu() { ContentWidget * cw = ui->longscroll->getContentWidget(); const QMetaObject * mo = cw->metaObject(); for (QAction * a : ui->menuProperties->actions()) { QMetaProperty const & prop = mo->property(a->data().toInt()); QString const & name = prop.name(); int type = prop.userType(); QVariant const & value = prop.read(cw); QString const & displayName = QString("%1 = %2").arg(name, prop.read(cw).toString()); a->setText(displayName); switch (type) { case QMetaType::Bool: a->setCheckable(true); a->setChecked(value.toBool()); break; default: break; } } } void MainWindow::propertyMenuTriggered(QAction * action) { for (QAction * a : demoGroup->actions()) a->setChecked(false); ContentWidget * cw = ui->longscroll->getContentWidget(); const QMetaObject * mo = cw->metaObject(); QMetaProperty const & prop = mo->property(action->data().toInt()); switch (prop.userType()) { case QMetaType::Bool: prop.write(cw, action->isChecked()); break; default: ValueEditDialog ved(this); ved.setValue(prop.name(), prop.read(cw)); if (ved.exec() == QDialog::Accepted) prop.write(cw, ved.getValue()); break; } } void MainWindow::demoMenuTriggered(QAction * action) { setDemoNumber(action->data().toInt()); } void MainWindow::on_actionOpen_triggered() { if (fileDialog == 0) { fileDialog = new QFileDialog(this); fileDialog->setAcceptMode(QFileDialog::AcceptOpen); fileDialog->setFileMode(QFileDialog::Directory); fileDialog->setOption(QFileDialog::ShowDirsOnly, true); } if (fileDialog->exec() != QDialog::Accepted) return; QDir dir(fileDialog->selectedFiles().first()); dir.makeAbsolute(); QFileInfo cacheInfo(dir.filePath("images.cache")); qDebug() << cacheInfo.absoluteFilePath() << cacheInfo.exists() << cacheInfo.isFile() << cacheInfo.isWritable() << cacheInfo.permissions(); QFileInfo dirInfo(dir.absolutePath()); qDebug() << dirInfo.absoluteFilePath() << dirInfo.isWritable() << dirInfo.permissions(); bool useCache = ((!cacheInfo.exists() && QFileInfo(dir.absolutePath()).isWritable()) || (cacheInfo.isFile() && cacheInfo.isWritable())); if (useCache && QMessageBox::question(this, tr("Write Cache File?"), tr("Write a cache file?\nThis is useful if you open a directory with a large number of files more than once.")) != QMessageBox::Yes) useCache = false; loadDir(dir, useCache); } void MainWindow::on_actionCount_triggered() { bool ok; int val = QInputDialog::getInt(this, "Count", "Fixed number of images", fixedInfoSize, 0, std::numeric_limits<int>::max(), 1, &ok); if (ok) setFixedItemCount(val); } void MainWindow::on_actionShuffle_triggered() { setItemInfos(itemInfos, fixedInfoSize, true); } <|endoftext|>
<commit_before>//===- Optimize.cpp - Optimize a complete program -------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Reid Spencer and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements all optimization of the linked module for llvm-ld. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Analysis/LoadValueNumbering.h" #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Support/CommandLine.h" #include "llvm/System/DynamicLibrary.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Support/PassNameParser.h" #include "llvm/Support/PluginLoader.h" #include <iostream> using namespace llvm; // Pass Name Options as generated by the PassNameParser static cl::list<const PassInfo*, bool, PassNameParser> OptimizationList(cl::desc("Optimizations available:")); // Optimization Enumeration enum OptimizationLevels { OPT_FAST_COMPILE = 1, OPT_SIMPLE = 2, OPT_AGGRESSIVE = 3, OPT_LINK_TIME = 4, OPT_AGGRESSIVE_LINK_TIME = 5 }; // Optimization Options static cl::opt<OptimizationLevels> OptLevel( cl::desc("Choose level of optimization to apply:"), cl::init(OPT_FAST_COMPILE), cl::values( clEnumValN(OPT_FAST_COMPILE,"O0", "An alias for the -O1 option."), clEnumValN(OPT_FAST_COMPILE,"O1", "Optimize for linking speed, not execution speed."), clEnumValN(OPT_SIMPLE,"O2", "Perform only required/minimal optimizations"), clEnumValN(OPT_AGGRESSIVE,"O3", "An alias for the -O2 option."), clEnumValN(OPT_LINK_TIME,"O4", "Perform standard link time optimizations"), clEnumValN(OPT_AGGRESSIVE_LINK_TIME,"O5", "Perform aggressive link time optimizations"), clEnumValEnd ) ); static cl::opt<bool> DisableInline("disable-inlining", cl::desc("Do not run the inliner pass")); static cl::opt<bool> DisableOptimizations("disable-opt", cl::desc("Do not run any optimization passes")); static cl::opt<bool> DisableInternalize("disable-internalize", cl::desc("Do not mark all symbols as internal")); static cl::opt<bool> VerifyEach("verify-each", cl::desc("Verify intermediate results of all passes")); static cl::alias ExportDynamic("export-dynamic", cl::aliasopt(DisableInternalize), cl::desc("Alias for -disable-internalize")); static cl::opt<bool> Strip("strip-all", cl::desc("Strip all symbol info from executable")); static cl::alias A0("s", cl::desc("Alias for --strip-all"), cl::aliasopt(Strip)); static cl::opt<bool> StripDebug("strip-debug", cl::desc("Strip debugger symbol info from executable")); static cl::alias A1("S", cl::desc("Alias for --strip-debug"), cl::aliasopt(StripDebug)); // A utility function that adds a pass to the pass manager but will also add // a verifier pass after if we're supposed to verify. static inline void addPass(PassManager &PM, Pass *P) { // Add the pass to the pass manager... PM.add(P); // If we are verifying all of the intermediate steps, add the verifier... if (VerifyEach) PM.add(createVerifierPass()); } namespace llvm { /// Optimize - Perform link time optimizations. This will run the scalar /// optimizations, any loaded plugin-optimization modules, and then the /// inter-procedural optimizations if applicable. void Optimize(Module* M) { // Instantiate the pass manager to organize the passes. PassManager Passes; // If we're verifying, start off with a verification pass. if (VerifyEach) Passes.add(createVerifierPass()); // Add an appropriate TargetData instance for this module... addPass(Passes, new TargetData(M)); if (!DisableOptimizations) { // Now that composite has been compiled, scan through the module, looking // for a main function. If main is defined, mark all other functions // internal. addPass(Passes, createInternalizePass(!DisableInternalize)); // Propagate constants at call sites into the functions they call. This // opens opportunities for globalopt (and inlining) by substituting function // pointers passed as arguments to direct uses of functions. addPass(Passes, createIPSCCPPass()); // Now that we internalized some globals, see if we can hack on them! addPass(Passes, createGlobalOptimizerPass()); // Linking modules together can lead to duplicated global constants, only // keep one copy of each constant... addPass(Passes, createConstantMergePass()); // Remove unused arguments from functions... addPass(Passes, createDeadArgEliminationPass()); // Reduce the code after globalopt and ipsccp. Both can open up significant // simplification opportunities, and both can propagate functions through // function pointers. When this happens, we often have to resolve varargs // calls, etc, so let instcombine do this. addPass(Passes, createInstructionCombiningPass()); if (!DisableInline) addPass(Passes, createFunctionInliningPass()); // Inline small functions addPass(Passes, createPruneEHPass()); // Remove dead EH info addPass(Passes, createGlobalOptimizerPass()); // Optimize globals again. addPass(Passes, createGlobalDCEPass()); // Remove dead functions // If we didn't decide to inline a function, check to see if we can // transform it to pass arguments by value instead of by reference. addPass(Passes, createArgumentPromotionPass()); // The IPO passes may leave cruft around. Clean up after them. addPass(Passes, createInstructionCombiningPass()); addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas // Run a few AA driven optimizations here and now, to cleanup the code. addPass(Passes, createGlobalsModRefPass()); // IP alias analysis addPass(Passes, createLICMPass()); // Hoist loop invariants addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs addPass(Passes, createGCSEPass()); // Remove common subexprs addPass(Passes, createDeadStoreEliminationPass()); // Nuke dead stores // Cleanup and simplify the code after the scalar optimizations. addPass(Passes, createInstructionCombiningPass()); // Delete basic blocks, which optimization passes may have killed... addPass(Passes, createCFGSimplificationPass()); // Now that we have optimized the program, discard unreachable functions... addPass(Passes, createGlobalDCEPass()); } // If the -s or -S command line options were specified, strip the symbols out // of the resulting program to make it smaller. -s and -S are GNU ld options // that we are supporting; they alias -strip-all and -strip-debug. if (Strip || StripDebug) addPass(Passes, createStripSymbolsPass(StripDebug && !Strip)); // Create a new optimization pass for each one specified on the command line std::auto_ptr<TargetMachine> target; for (unsigned i = 0; i < OptimizationList.size(); ++i) { const PassInfo *Opt = OptimizationList[i]; if (Opt->getNormalCtor()) addPass(Passes, Opt->getNormalCtor()()); else std::cerr << "llvm-ld: cannot create pass: " << Opt->getPassName() << "\n"; } // The user's passes may leave cruft around. Clean up after them them but // only if we haven't got DisableOptimizations set if (!DisableOptimizations) { addPass(Passes, createInstructionCombiningPass()); addPass(Passes, createCFGSimplificationPass()); addPass(Passes, createGlobalDCEPass()); } // Make sure everything is still good. Passes.add(createVerifierPass()); // Run our queue of passes all at once now, efficiently. Passes.run(*M); } } <commit_msg>run a late dce pass to clean up extra cruft.<commit_after>//===- Optimize.cpp - Optimize a complete program -------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Reid Spencer and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements all optimization of the linked module for llvm-ld. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Analysis/LoadValueNumbering.h" #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Support/CommandLine.h" #include "llvm/System/DynamicLibrary.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Support/PassNameParser.h" #include "llvm/Support/PluginLoader.h" #include <iostream> using namespace llvm; // Pass Name Options as generated by the PassNameParser static cl::list<const PassInfo*, bool, PassNameParser> OptimizationList(cl::desc("Optimizations available:")); // Optimization Enumeration enum OptimizationLevels { OPT_FAST_COMPILE = 1, OPT_SIMPLE = 2, OPT_AGGRESSIVE = 3, OPT_LINK_TIME = 4, OPT_AGGRESSIVE_LINK_TIME = 5 }; // Optimization Options static cl::opt<OptimizationLevels> OptLevel( cl::desc("Choose level of optimization to apply:"), cl::init(OPT_FAST_COMPILE), cl::values( clEnumValN(OPT_FAST_COMPILE,"O0", "An alias for the -O1 option."), clEnumValN(OPT_FAST_COMPILE,"O1", "Optimize for linking speed, not execution speed."), clEnumValN(OPT_SIMPLE,"O2", "Perform only required/minimal optimizations"), clEnumValN(OPT_AGGRESSIVE,"O3", "An alias for the -O2 option."), clEnumValN(OPT_LINK_TIME,"O4", "Perform standard link time optimizations"), clEnumValN(OPT_AGGRESSIVE_LINK_TIME,"O5", "Perform aggressive link time optimizations"), clEnumValEnd ) ); static cl::opt<bool> DisableInline("disable-inlining", cl::desc("Do not run the inliner pass")); static cl::opt<bool> DisableOptimizations("disable-opt", cl::desc("Do not run any optimization passes")); static cl::opt<bool> DisableInternalize("disable-internalize", cl::desc("Do not mark all symbols as internal")); static cl::opt<bool> VerifyEach("verify-each", cl::desc("Verify intermediate results of all passes")); static cl::alias ExportDynamic("export-dynamic", cl::aliasopt(DisableInternalize), cl::desc("Alias for -disable-internalize")); static cl::opt<bool> Strip("strip-all", cl::desc("Strip all symbol info from executable")); static cl::alias A0("s", cl::desc("Alias for --strip-all"), cl::aliasopt(Strip)); static cl::opt<bool> StripDebug("strip-debug", cl::desc("Strip debugger symbol info from executable")); static cl::alias A1("S", cl::desc("Alias for --strip-debug"), cl::aliasopt(StripDebug)); // A utility function that adds a pass to the pass manager but will also add // a verifier pass after if we're supposed to verify. static inline void addPass(PassManager &PM, Pass *P) { // Add the pass to the pass manager... PM.add(P); // If we are verifying all of the intermediate steps, add the verifier... if (VerifyEach) PM.add(createVerifierPass()); } namespace llvm { /// Optimize - Perform link time optimizations. This will run the scalar /// optimizations, any loaded plugin-optimization modules, and then the /// inter-procedural optimizations if applicable. void Optimize(Module* M) { // Instantiate the pass manager to organize the passes. PassManager Passes; // If we're verifying, start off with a verification pass. if (VerifyEach) Passes.add(createVerifierPass()); // Add an appropriate TargetData instance for this module... addPass(Passes, new TargetData(M)); if (!DisableOptimizations) { // Now that composite has been compiled, scan through the module, looking // for a main function. If main is defined, mark all other functions // internal. addPass(Passes, createInternalizePass(!DisableInternalize)); // Propagate constants at call sites into the functions they call. This // opens opportunities for globalopt (and inlining) by substituting function // pointers passed as arguments to direct uses of functions. addPass(Passes, createIPSCCPPass()); // Now that we internalized some globals, see if we can hack on them! addPass(Passes, createGlobalOptimizerPass()); // Linking modules together can lead to duplicated global constants, only // keep one copy of each constant... addPass(Passes, createConstantMergePass()); // Remove unused arguments from functions... addPass(Passes, createDeadArgEliminationPass()); // Reduce the code after globalopt and ipsccp. Both can open up significant // simplification opportunities, and both can propagate functions through // function pointers. When this happens, we often have to resolve varargs // calls, etc, so let instcombine do this. addPass(Passes, createInstructionCombiningPass()); if (!DisableInline) addPass(Passes, createFunctionInliningPass()); // Inline small functions addPass(Passes, createPruneEHPass()); // Remove dead EH info addPass(Passes, createGlobalOptimizerPass()); // Optimize globals again. addPass(Passes, createGlobalDCEPass()); // Remove dead functions // If we didn't decide to inline a function, check to see if we can // transform it to pass arguments by value instead of by reference. addPass(Passes, createArgumentPromotionPass()); // The IPO passes may leave cruft around. Clean up after them. addPass(Passes, createInstructionCombiningPass()); addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas // Run a few AA driven optimizations here and now, to cleanup the code. addPass(Passes, createGlobalsModRefPass()); // IP alias analysis addPass(Passes, createLICMPass()); // Hoist loop invariants addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs addPass(Passes, createGCSEPass()); // Remove common subexprs addPass(Passes, createDeadStoreEliminationPass()); // Nuke dead stores // Cleanup and simplify the code after the scalar optimizations. addPass(Passes, createInstructionCombiningPass()); // Delete basic blocks, which optimization passes may have killed... addPass(Passes, createCFGSimplificationPass()); // Now that we have optimized the program, discard unreachable functions... addPass(Passes, createGlobalDCEPass()); } // If the -s or -S command line options were specified, strip the symbols out // of the resulting program to make it smaller. -s and -S are GNU ld options // that we are supporting; they alias -strip-all and -strip-debug. if (Strip || StripDebug) addPass(Passes, createStripSymbolsPass(StripDebug && !Strip)); // Create a new optimization pass for each one specified on the command line std::auto_ptr<TargetMachine> target; for (unsigned i = 0; i < OptimizationList.size(); ++i) { const PassInfo *Opt = OptimizationList[i]; if (Opt->getNormalCtor()) addPass(Passes, Opt->getNormalCtor()()); else std::cerr << "llvm-ld: cannot create pass: " << Opt->getPassName() << "\n"; } // The user's passes may leave cruft around. Clean up after them them but // only if we haven't got DisableOptimizations set if (!DisableOptimizations) { addPass(Passes, createInstructionCombiningPass()); addPass(Passes, createCFGSimplificationPass()); addPass(Passes, createDeadCodeEliminationPass()); addPass(Passes, createGlobalDCEPass()); } // Make sure everything is still good. Passes.add(createVerifierPass()); // Run our queue of passes all at once now, efficiently. Passes.run(*M); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MNSTerminateListener.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 03:01:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #ifndef _MNSTERMINATELISTENER_HXX #include <MNSTerminateListener.hxx> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_ #include <com/sun/star/frame/XDesktop.hpp> #endif #ifndef _CONNECTIVITY_MAB_NS_INIT_HXX_ #include <MNSInit.hxx> #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::frame; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XTerminateListener> MNSTerminateListener::mxTerminateListener = new MNSTerminateListener(); // ----------------------------------------- // - MNSTerminateListener - // ----------------------------------------- MNSTerminateListener::MNSTerminateListener( ) { } // ----------------------------------------------------------------------------- MNSTerminateListener::~MNSTerminateListener() { } // ----------------------------------------------------------------------------- void SAL_CALL MNSTerminateListener::disposing( const EventObject& /*Source*/ ) throw( RuntimeException ) { } // ----------------------------------------------------------------------------- void SAL_CALL MNSTerminateListener::queryTermination( const EventObject& /*aEvent*/ ) throw( TerminationVetoException, RuntimeException ) { } // ----------------------------------------------------------------------------- void SAL_CALL MNSTerminateListener::notifyTermination( const EventObject& /*aEvent*/ ) throw( RuntimeException ) { MNS_Term(sal_True); //Force XPCOM to shutdown } void MNSTerminateListener::addTerminateListener() { Reference< XMultiServiceFactory > xFact( ::comphelper::getProcessServiceFactory() ); if( xFact.is() ) { Reference< XDesktop > xDesktop( xFact->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.frame.Desktop" ) ), UNO_QUERY ); if( xDesktop.is() ) xDesktop->addTerminateListener(mxTerminateListener); } } <commit_msg>INTEGRATION: CWS changefileheader (1.5.216); FILE MERGED 2008/04/01 15:09:01 thb 1.5.216.3: #i85898# Stripping all external header guards 2008/04/01 10:53:13 thb 1.5.216.2: #i85898# Stripping all external header guards 2008/03/28 15:23:58 rt 1.5.216.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MNSTerminateListener.cxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include <MNSTerminateListener.hxx> #include <comphelper/processfactory.hxx> #include <com/sun/star/frame/XDesktop.hpp> #include <MNSInit.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::frame; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XTerminateListener> MNSTerminateListener::mxTerminateListener = new MNSTerminateListener(); // ----------------------------------------- // - MNSTerminateListener - // ----------------------------------------- MNSTerminateListener::MNSTerminateListener( ) { } // ----------------------------------------------------------------------------- MNSTerminateListener::~MNSTerminateListener() { } // ----------------------------------------------------------------------------- void SAL_CALL MNSTerminateListener::disposing( const EventObject& /*Source*/ ) throw( RuntimeException ) { } // ----------------------------------------------------------------------------- void SAL_CALL MNSTerminateListener::queryTermination( const EventObject& /*aEvent*/ ) throw( TerminationVetoException, RuntimeException ) { } // ----------------------------------------------------------------------------- void SAL_CALL MNSTerminateListener::notifyTermination( const EventObject& /*aEvent*/ ) throw( RuntimeException ) { MNS_Term(sal_True); //Force XPCOM to shutdown } void MNSTerminateListener::addTerminateListener() { Reference< XMultiServiceFactory > xFact( ::comphelper::getProcessServiceFactory() ); if( xFact.is() ) { Reference< XDesktop > xDesktop( xFact->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.frame.Desktop" ) ), UNO_QUERY ); if( xDesktop.is() ) xDesktop->addTerminateListener(mxTerminateListener); } } <|endoftext|>
<commit_before>//===--- ParameterPack.cpp - Utilities for variadic generics --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements utilities for substituting type parameter packs // appearing in pack expansion types. // //===----------------------------------------------------------------------===// #include "swift/AST/ASTContext.h" #include "swift/AST/Decl.h" #include "swift/AST/ParameterList.h" #include "swift/AST/Type.h" #include "swift/AST/Types.h" #include "llvm/ADT/SmallVector.h" using namespace swift; namespace { /// Collects all unique pack type parameters referenced from the pattern type, /// skipping those captured by nested pack expansion types. struct PackTypeParameterCollector: TypeWalker { llvm::SetVector<Type> typeParams; Action walkToTypePre(Type t) override { if (t->is<PackExpansionType>()) return Action::SkipChildren; if (auto *paramTy = t->getAs<GenericTypeParamType>()) { if (paramTy->isParameterPack()) typeParams.insert(paramTy); } else if (auto *archetypeTy = t->getAs<PackArchetypeType>()) { if (archetypeTy->isRoot()) typeParams.insert(paramTy); } return Action::Continue; } }; } void TypeBase::getTypeParameterPacks( SmallVectorImpl<Type> &rootParameterPacks) { PackTypeParameterCollector collector; Type(this).walk(collector); rootParameterPacks.append(collector.typeParams.begin(), collector.typeParams.end()); } bool GenericTypeParamType::isParameterPack() const { if (auto param = getDecl()) { return param->isParameterPack(); } auto fixedNum = ParamOrDepthIndex.get<DepthIndexTy>(); return (fixedNum & GenericTypeParamType::TYPE_SEQUENCE_BIT) == GenericTypeParamType::TYPE_SEQUENCE_BIT; } GenericTypeParamType * GenericTypeParamType::asParameterPack(ASTContext &ctx) const { return GenericTypeParamType::get(/*isParameterPack*/true, getDepth(), getIndex(), ctx); } GenericTypeParamType * GenericTypeParamType::asScalar(ASTContext &ctx) const { return GenericTypeParamType::get(/*isParameterPack*/false, getDepth(), getIndex(), ctx); } /// G<{X1, ..., Xn}, {Y1, ..., Yn}>... => {G<X1, Y1>, ..., G<Xn, Yn>}... PackExpansionType *PackExpansionType::expand() { auto countType = getCountType(); auto *countPack = countType->getAs<PackType>(); if (countPack == nullptr) return this; auto patternType = getPatternType(); if (patternType->is<PackType>()) return this; unsigned j = 0; SmallVector<Type, 4> expandedTypes; for (auto type : countPack->getElementTypes()) { Type expandedCount; if (auto *expansion = type->getAs<PackExpansionType>()) expandedCount = expansion->getCountType(); auto expandedPattern = patternType.transformRec( [&](Type t) -> Optional<Type> { if (t->is<PackExpansionType>()) return t; if (auto *nestedPack = t->getAs<PackType>()) { auto nestedPackElts = nestedPack->getElementTypes(); if (j < nestedPackElts.size()) { if (expandedCount) { if (auto *expansion = nestedPackElts[j]->getAs<PackExpansionType>()) return expansion->getPatternType(); } else { return nestedPackElts[j]; } } return ErrorType::get(t->getASTContext()); } return None; }); if (expandedCount) { expandedTypes.push_back(PackExpansionType::get(expandedPattern, expandedCount)); } else { expandedTypes.push_back(expandedPattern); } ++j; } auto *packType = PackType::get(getASTContext(), expandedTypes); return PackExpansionType::get(packType, countType); } CanType PackExpansionType::getReducedShape() { if (auto *archetypeType = countType->getAs<PackArchetypeType>()) { auto shape = archetypeType->getReducedShape(); return CanType(PackExpansionType::get(shape, shape)); } else if (auto *packType = countType->getAs<PackType>()) { auto shape = packType->getReducedShape(); return CanType(PackExpansionType::get(shape, shape)); } assert(countType->is<PlaceholderType>()); return getASTContext().TheEmptyTupleType; } bool TupleType::containsPackExpansionType() const { for (auto elt : getElements()) { if (elt.getType()->is<PackExpansionType>()) return true; } return false; } /// (W, {X, Y}..., Z) => (W, X, Y, Z) TupleType *TupleType::flattenPackTypes() { bool anyChanged = false; SmallVector<TupleTypeElt, 4> elts; for (unsigned i = 0, e = getNumElements(); i < e; ++i) { auto elt = getElement(i); if (auto *expansionType = elt.getType()->getAs<PackExpansionType>()) { if (auto *packType = expansionType->getPatternType()->getAs<PackType>()) { if (!anyChanged) { elts.append(getElements().begin(), getElements().begin() + i); anyChanged = true; } bool first = true; for (auto packElt : packType->getElementTypes()) { if (first) { elts.push_back(TupleTypeElt(packElt, elt.getName())); first = false; continue; } elts.push_back(TupleTypeElt(packElt)); } continue; } } if (anyChanged) elts.push_back(elt); } if (!anyChanged) return this; return TupleType::get(elts, getASTContext()); } bool AnyFunctionType::containsPackExpansionType(ArrayRef<Param> params) { for (auto param : params) { if (param.getPlainType()->is<PackExpansionType>()) return true; } return false; } /// (W, {X, Y}..., Z) -> T => (W, X, Y, Z) -> T AnyFunctionType *AnyFunctionType::flattenPackTypes() { bool anyChanged = false; SmallVector<AnyFunctionType::Param, 4> params; for (unsigned i = 0, e = getParams().size(); i < e; ++i) { auto param = getParams()[i]; if (auto *expansionType = param.getPlainType()->getAs<PackExpansionType>()) { if (auto *packType = expansionType->getPatternType()->getAs<PackType>()) { if (!anyChanged) { params.append(getParams().begin(), getParams().begin() + i); anyChanged = true; } bool first = true; for (auto packElt : packType->getElementTypes()) { if (first) { params.push_back(param.withType(packElt)); first = false; continue; } params.push_back(param.withType(packElt).getWithoutLabels()); } continue; } } if (anyChanged) params.push_back(param); } if (!anyChanged) return this; if (auto *genericFuncType = getAs<GenericFunctionType>()) { return GenericFunctionType::get(genericFuncType->getGenericSignature(), params, getResult(), getExtInfo()); } else { return FunctionType::get(params, getResult(), getExtInfo()); } } bool PackType::containsPackExpansionType() const { for (auto type : getElementTypes()) { if (type->is<PackExpansionType>()) return true; } return false; } /// {W, {X, Y}..., Z} => {W, X, Y, Z} PackType *PackType::flattenPackTypes() { bool anyChanged = false; SmallVector<Type, 4> elts; for (unsigned i = 0, e = getNumElements(); i < e; ++i) { auto elt = getElementType(i); if (auto *expansionType = elt->getAs<PackExpansionType>()) { if (auto *packType = expansionType->getPatternType()->getAs<PackType>()) { if (!anyChanged) { elts.append(getElementTypes().begin(), getElementTypes().begin() + i); anyChanged = true; } for (auto packElt : packType->getElementTypes()) { elts.push_back(packElt); } continue; } } if (anyChanged) elts.push_back(elt); } if (!anyChanged) return this; return PackType::get(getASTContext(), elts); } CanPackType PackType::getReducedShape() { SmallVector<Type, 4> elts; auto &ctx = getASTContext(); for (auto elt : getElementTypes()) { // T... => shape(T)... if (auto *packExpansionType = elt->getAs<PackExpansionType>()) { elts.push_back(packExpansionType->getReducedShape()); continue; } // Use () as a placeholder for scalar shape. assert(!elt->is<PackArchetypeType>() && "Pack archetype outside of a pack expansion"); elts.push_back(ctx.TheEmptyTupleType); } return CanPackType(PackType::get(ctx, elts)); } CanType TypeBase::getReducedShape() { if (auto *packType = getAs<PackType>()) return packType->getReducedShape(); if (auto *expansionType = getAs<PackExpansionType>()) return expansionType->getReducedShape(); struct PatternTypeWalker : public TypeWalker { CanType shapeType; Action walkToTypePre(Type type) override { // Don't consider pack references inside nested pack // expansion types. if (type->is<PackExpansionType>()) { return Action::Stop; } if (auto *archetype = type->getAs<PackArchetypeType>()) { shapeType = archetype->getReducedShape(); return Action::Stop; } return Action::Continue; } } patternTypeWalker; Type(this).walk(patternTypeWalker); if (patternTypeWalker.shapeType) return patternTypeWalker.shapeType; assert(!isTypeVariableOrMember()); assert(!hasTypeParameter()); // Use () as a placeholder for scalar shape. return getASTContext().TheEmptyTupleType; } unsigned ParameterList::getOrigParamIndex(SubstitutionMap subMap, unsigned substIndex) const { unsigned remappedIndex = substIndex; for (unsigned i = 0, e = size(); i < e; ++i) { auto *param = get(i); auto paramType = param->getInterfaceType(); unsigned substCount = 1; if (auto *packExpansionType = paramType->getAs<PackExpansionType>()) { auto replacementType = packExpansionType->getCountType().subst(subMap); if (auto *packType = replacementType->getAs<PackType>()) { substCount = packType->getNumElements(); } } if (remappedIndex < substCount) return i; remappedIndex -= substCount; } llvm::errs() << "Invalid substituted argument index: " << substIndex << "\n"; subMap.dump(llvm::errs()); dump(llvm::errs()); abort(); } <commit_msg>[ParameterPack] Use the 'getTypeParameterPacks' utility when computing the reduced shape of a given type that is not directly a pack type or archetype.<commit_after>//===--- ParameterPack.cpp - Utilities for variadic generics --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements utilities for substituting type parameter packs // appearing in pack expansion types. // //===----------------------------------------------------------------------===// #include "swift/AST/ASTContext.h" #include "swift/AST/Decl.h" #include "swift/AST/ParameterList.h" #include "swift/AST/Type.h" #include "swift/AST/Types.h" #include "llvm/ADT/SmallVector.h" using namespace swift; namespace { /// Collects all unique pack type parameters referenced from the pattern type, /// skipping those captured by nested pack expansion types. struct PackTypeParameterCollector: TypeWalker { llvm::SetVector<Type> typeParams; Action walkToTypePre(Type t) override { if (t->is<PackExpansionType>()) return Action::SkipChildren; if (auto *paramTy = t->getAs<GenericTypeParamType>()) { if (paramTy->isParameterPack()) typeParams.insert(paramTy); } else if (auto *archetypeTy = t->getAs<PackArchetypeType>()) { typeParams.insert(archetypeTy->getRoot()); } return Action::Continue; } }; } void TypeBase::getTypeParameterPacks( SmallVectorImpl<Type> &rootParameterPacks) { PackTypeParameterCollector collector; Type(this).walk(collector); rootParameterPacks.append(collector.typeParams.begin(), collector.typeParams.end()); } bool GenericTypeParamType::isParameterPack() const { if (auto param = getDecl()) { return param->isParameterPack(); } auto fixedNum = ParamOrDepthIndex.get<DepthIndexTy>(); return (fixedNum & GenericTypeParamType::TYPE_SEQUENCE_BIT) == GenericTypeParamType::TYPE_SEQUENCE_BIT; } GenericTypeParamType * GenericTypeParamType::asParameterPack(ASTContext &ctx) const { return GenericTypeParamType::get(/*isParameterPack*/true, getDepth(), getIndex(), ctx); } GenericTypeParamType * GenericTypeParamType::asScalar(ASTContext &ctx) const { return GenericTypeParamType::get(/*isParameterPack*/false, getDepth(), getIndex(), ctx); } /// G<{X1, ..., Xn}, {Y1, ..., Yn}>... => {G<X1, Y1>, ..., G<Xn, Yn>}... PackExpansionType *PackExpansionType::expand() { auto countType = getCountType(); auto *countPack = countType->getAs<PackType>(); if (countPack == nullptr) return this; auto patternType = getPatternType(); if (patternType->is<PackType>()) return this; unsigned j = 0; SmallVector<Type, 4> expandedTypes; for (auto type : countPack->getElementTypes()) { Type expandedCount; if (auto *expansion = type->getAs<PackExpansionType>()) expandedCount = expansion->getCountType(); auto expandedPattern = patternType.transformRec( [&](Type t) -> Optional<Type> { if (t->is<PackExpansionType>()) return t; if (auto *nestedPack = t->getAs<PackType>()) { auto nestedPackElts = nestedPack->getElementTypes(); if (j < nestedPackElts.size()) { if (expandedCount) { if (auto *expansion = nestedPackElts[j]->getAs<PackExpansionType>()) return expansion->getPatternType(); } else { return nestedPackElts[j]; } } return ErrorType::get(t->getASTContext()); } return None; }); if (expandedCount) { expandedTypes.push_back(PackExpansionType::get(expandedPattern, expandedCount)); } else { expandedTypes.push_back(expandedPattern); } ++j; } auto *packType = PackType::get(getASTContext(), expandedTypes); return PackExpansionType::get(packType, countType); } CanType PackExpansionType::getReducedShape() { if (auto *archetypeType = countType->getAs<PackArchetypeType>()) { auto shape = archetypeType->getReducedShape(); return CanType(PackExpansionType::get(shape, shape)); } else if (auto *packType = countType->getAs<PackType>()) { auto shape = packType->getReducedShape(); return CanType(PackExpansionType::get(shape, shape)); } assert(countType->is<PlaceholderType>()); return getASTContext().TheEmptyTupleType; } bool TupleType::containsPackExpansionType() const { for (auto elt : getElements()) { if (elt.getType()->is<PackExpansionType>()) return true; } return false; } /// (W, {X, Y}..., Z) => (W, X, Y, Z) TupleType *TupleType::flattenPackTypes() { bool anyChanged = false; SmallVector<TupleTypeElt, 4> elts; for (unsigned i = 0, e = getNumElements(); i < e; ++i) { auto elt = getElement(i); if (auto *expansionType = elt.getType()->getAs<PackExpansionType>()) { if (auto *packType = expansionType->getPatternType()->getAs<PackType>()) { if (!anyChanged) { elts.append(getElements().begin(), getElements().begin() + i); anyChanged = true; } bool first = true; for (auto packElt : packType->getElementTypes()) { if (first) { elts.push_back(TupleTypeElt(packElt, elt.getName())); first = false; continue; } elts.push_back(TupleTypeElt(packElt)); } continue; } } if (anyChanged) elts.push_back(elt); } if (!anyChanged) return this; return TupleType::get(elts, getASTContext()); } bool AnyFunctionType::containsPackExpansionType(ArrayRef<Param> params) { for (auto param : params) { if (param.getPlainType()->is<PackExpansionType>()) return true; } return false; } /// (W, {X, Y}..., Z) -> T => (W, X, Y, Z) -> T AnyFunctionType *AnyFunctionType::flattenPackTypes() { bool anyChanged = false; SmallVector<AnyFunctionType::Param, 4> params; for (unsigned i = 0, e = getParams().size(); i < e; ++i) { auto param = getParams()[i]; if (auto *expansionType = param.getPlainType()->getAs<PackExpansionType>()) { if (auto *packType = expansionType->getPatternType()->getAs<PackType>()) { if (!anyChanged) { params.append(getParams().begin(), getParams().begin() + i); anyChanged = true; } bool first = true; for (auto packElt : packType->getElementTypes()) { if (first) { params.push_back(param.withType(packElt)); first = false; continue; } params.push_back(param.withType(packElt).getWithoutLabels()); } continue; } } if (anyChanged) params.push_back(param); } if (!anyChanged) return this; if (auto *genericFuncType = getAs<GenericFunctionType>()) { return GenericFunctionType::get(genericFuncType->getGenericSignature(), params, getResult(), getExtInfo()); } else { return FunctionType::get(params, getResult(), getExtInfo()); } } bool PackType::containsPackExpansionType() const { for (auto type : getElementTypes()) { if (type->is<PackExpansionType>()) return true; } return false; } /// {W, {X, Y}..., Z} => {W, X, Y, Z} PackType *PackType::flattenPackTypes() { bool anyChanged = false; SmallVector<Type, 4> elts; for (unsigned i = 0, e = getNumElements(); i < e; ++i) { auto elt = getElementType(i); if (auto *expansionType = elt->getAs<PackExpansionType>()) { if (auto *packType = expansionType->getPatternType()->getAs<PackType>()) { if (!anyChanged) { elts.append(getElementTypes().begin(), getElementTypes().begin() + i); anyChanged = true; } for (auto packElt : packType->getElementTypes()) { elts.push_back(packElt); } continue; } } if (anyChanged) elts.push_back(elt); } if (!anyChanged) return this; return PackType::get(getASTContext(), elts); } CanPackType PackType::getReducedShape() { SmallVector<Type, 4> elts; auto &ctx = getASTContext(); for (auto elt : getElementTypes()) { // T... => shape(T)... if (auto *packExpansionType = elt->getAs<PackExpansionType>()) { elts.push_back(packExpansionType->getReducedShape()); continue; } // Use () as a placeholder for scalar shape. assert(!elt->is<PackArchetypeType>() && "Pack archetype outside of a pack expansion"); elts.push_back(ctx.TheEmptyTupleType); } return CanPackType(PackType::get(ctx, elts)); } CanType TypeBase::getReducedShape() { if (auto *packArchetype = getAs<PackArchetypeType>()) return packArchetype->getReducedShape(); if (auto *packType = getAs<PackType>()) return packType->getReducedShape(); if (auto *expansionType = getAs<PackExpansionType>()) return expansionType->getReducedShape(); SmallVector<Type, 2> rootParameterPacks; getTypeParameterPacks(rootParameterPacks); if (!rootParameterPacks.empty()) return rootParameterPacks.front()->getReducedShape(); assert(!isTypeVariableOrMember()); assert(!hasTypeParameter()); // Use () as a placeholder for scalar shape. return getASTContext().TheEmptyTupleType; } unsigned ParameterList::getOrigParamIndex(SubstitutionMap subMap, unsigned substIndex) const { unsigned remappedIndex = substIndex; for (unsigned i = 0, e = size(); i < e; ++i) { auto *param = get(i); auto paramType = param->getInterfaceType(); unsigned substCount = 1; if (auto *packExpansionType = paramType->getAs<PackExpansionType>()) { auto replacementType = packExpansionType->getCountType().subst(subMap); if (auto *packType = replacementType->getAs<PackType>()) { substCount = packType->getNumElements(); } } if (remappedIndex < substCount) return i; remappedIndex -= substCount; } llvm::errs() << "Invalid substituted argument index: " << substIndex << "\n"; subMap.dump(llvm::errs()); dump(llvm::errs()); abort(); } <|endoftext|>
<commit_before>//===--- USRGeneration.cpp - Routines for USR generation ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/AST/ASTContext.h" #include "swift/AST/ClangModuleLoader.h" #include "swift/AST/Module.h" #include "swift/AST/USRGeneration.h" #include "swift/AST/ASTMangler.h" #include "swift/AST/SwiftNameTranslation.h" #include "swift/AST/TypeCheckRequests.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/raw_ostream.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Attr.h" #include "clang/Index/USRGeneration.h" #include "clang/Lex/PreprocessingRecord.h" #include "clang/Lex/Preprocessor.h" using namespace swift; using namespace ide; static inline StringRef getUSRSpacePrefix() { return "s:"; } bool ide::printTypeUSR(Type Ty, raw_ostream &OS) { assert(!Ty->hasArchetype() && "cannot have contextless archetypes mangled."); Mangle::ASTMangler Mangler; OS << Mangler.mangleTypeAsUSR(Ty->getRValueType()); return false; } bool ide::printDeclTypeUSR(const ValueDecl *D, raw_ostream &OS) { Mangle::ASTMangler Mangler; std::string MangledName = Mangler.mangleDeclType(D); OS << MangledName; return false; } static bool printObjCUSRFragment(const ValueDecl *D, StringRef ObjCName, const ExtensionDecl *ExtContextD, raw_ostream &OS) { if (!D) return true; // The Swift module name that the decl originated from. If the decl is // originating from ObjC code (ObjC module or the bridging header) then this // will be empty. StringRef ModuleName; if (!D->hasClangNode()) ModuleName = D->getModuleContext()->getNameStr(); if (isa<ClassDecl>(D)) { StringRef extContextName; if (ExtContextD) { extContextName = ExtContextD->getModuleContext()->getNameStr(); } clang::index::generateUSRForObjCClass(ObjCName, OS, ModuleName, extContextName); } else if (isa<ProtocolDecl>(D)) { clang::index::generateUSRForObjCProtocol(ObjCName, OS, ModuleName); } else if (isa<VarDecl>(D)) { clang::index::generateUSRForObjCProperty(ObjCName, D->isStatic(), OS); } else if (isa<ConstructorDecl>(D)) { // init() is a class member in Swift, but an instance method in ObjC. clang::index::generateUSRForObjCMethod(ObjCName, /*IsInstanceMethod=*/true, OS); } else if (isa<AbstractFunctionDecl>(D)) { clang::index::generateUSRForObjCMethod(ObjCName, D->isInstanceMember(), OS); } else if (isa<EnumDecl>(D)) { clang::index::generateUSRForGlobalEnum(ObjCName, OS, ModuleName); } else if (isa<EnumElementDecl>(D)) { clang::index::generateUSRForEnumConstant(ObjCName, OS); } else { llvm_unreachable("Unexpected value decl"); } return false; } static bool printObjCUSRContext(const Decl *D, raw_ostream &OS) { OS << clang::index::getUSRSpacePrefix(); auto *DC = D->getDeclContext(); if (auto *Parent = DC->getSelfNominalTypeDecl()) { auto *extContextD = dyn_cast<ExtensionDecl>(DC); auto ObjCName = objc_translation::getObjCNameForSwiftDecl(Parent); if (printObjCUSRFragment(Parent, ObjCName.first.str(), extContextD, OS)) return true; } return false; } static bool printObjCUSRForAccessor(const AbstractStorageDecl *ASD, AccessorKind Kind, raw_ostream &OS) { if (printObjCUSRContext(ASD, OS)) return true; ObjCSelector Selector; switch (Kind) { case swift::AccessorKind::Get: Selector = ASD->getObjCGetterSelector(); break; case swift::AccessorKind::Set: Selector = ASD->getObjCSetterSelector(); break; default: llvm_unreachable("invalid accessor kind"); } assert(Selector); llvm::SmallString<128> Buf; clang::index::generateUSRForObjCMethod(Selector.getString(Buf), ASD->isInstanceMember(), OS); return false; } static bool printObjCUSR(const ValueDecl *D, raw_ostream &OS) { if (printObjCUSRContext(D, OS)) return true; auto *extContextD = dyn_cast<ExtensionDecl>(D->getDeclContext()); auto ObjCName = objc_translation::getObjCNameForSwiftDecl(D); if (!ObjCName.first.empty()) return printObjCUSRFragment(D, ObjCName.first.str(), extContextD, OS); assert(ObjCName.second); llvm::SmallString<128> Buf; return printObjCUSRFragment(D, ObjCName.second.getString(Buf), extContextD, OS); } static bool shouldUseObjCUSR(const Decl *D) { // Only the subscript getter/setter are visible to ObjC rather than the // subscript itself if (isa<SubscriptDecl>(D)) return false; auto Parent = D->getDeclContext()->getInnermostDeclarationDeclContext(); if (Parent && (!shouldUseObjCUSR(Parent) || // parent should be visible too !D->getDeclContext()->isTypeContext() || // no local decls isa<TypeDecl>(D))) // nested types aren't supported return false; if (const auto *VD = dyn_cast<ValueDecl>(D)) { if (isa<EnumElementDecl>(VD)) return true; return objc_translation::isVisibleToObjC(VD, AccessLevel::Internal); } if (const auto *ED = dyn_cast<ExtensionDecl>(D)) { if (auto baseClass = ED->getSelfClassDecl()) { return shouldUseObjCUSR(baseClass) && !baseClass->isForeign(); } } return false; } llvm::Expected<std::string> swift::USRGenerationRequest::evaluate(Evaluator &evaluator, const ValueDecl *D) const { if (auto *VD = dyn_cast<VarDecl>(D)) D = VD->getCanonicalVarDecl(); if (!D->hasName() && !isa<ParamDecl>(D) && !isa<AccessorDecl>(D)) return std::string(); // Ignore. if (D->getModuleContext()->isBuiltinModule()) return std::string(); // Ignore. if (isa<ModuleDecl>(D)) return std::string(); // Ignore. auto interpretAsClangNode = [](const ValueDecl *D)->ClangNode { ClangNode ClangN = D->getClangNode(); if (auto ClangD = ClangN.getAsDecl()) { // NSErrorDomain causes the clang enum to be imported like this: // // struct MyError { // enum Code : Int32 { // case errFirst // case errSecond // } // static var errFirst: MyError.Code { get } // static var errSecond: MyError.Code { get } // } // // The clang enum constants are associated with both the static vars and // the enum cases. // But we want unique USRs for the above symbols, so use the clang USR // for the enum cases, and the Swift USR for the vars. // if (auto *ClangEnumConst = dyn_cast<clang::EnumConstantDecl>(ClangD)) { if (auto *ClangEnum = dyn_cast<clang::EnumDecl>(ClangEnumConst->getDeclContext())) { if (ClangEnum->hasAttr<clang::NSErrorDomainAttr>() && isa<VarDecl>(D)) return ClangNode(); } } } return ClangN; }; llvm::SmallString<128> Buffer; llvm::raw_svector_ostream OS(Buffer); if (ClangNode ClangN = interpretAsClangNode(D)) { if (auto ClangD = ClangN.getAsDecl()) { bool Ignore = clang::index::generateUSRForDecl(ClangD, Buffer); if (!Ignore) { return Buffer.str(); } else { return std::string(); } } auto &Importer = *D->getASTContext().getClangModuleLoader(); auto ClangMacroInfo = ClangN.getAsMacro(); bool Ignore = clang::index::generateUSRForMacro( D->getBaseName().getIdentifier().str(), ClangMacroInfo->getDefinitionLoc(), Importer.getClangASTContext().getSourceManager(), Buffer); if (!Ignore) return Buffer.str(); else return std::string(); } if (shouldUseObjCUSR(D)) { if (printObjCUSR(D, OS)) { return std::string(); } else { return OS.str(); } } auto declIFaceTy = D->getInterfaceType(); if (!declIFaceTy) return std::string(); // Invalid code. if (declIFaceTy.findIf([](Type t) -> bool { return t->is<ModuleType>(); })) return std::string(); Mangle::ASTMangler NewMangler; return NewMangler.mangleDeclAsUSR(D, getUSRSpacePrefix()); } llvm::Expected<std::string> swift::MangleLocalTypeDeclRequest::evaluate(Evaluator &evaluator, const TypeDecl *D) const { if (!D->hasInterfaceType()) return std::string(); if (isa<ModuleDecl>(D)) return std::string(); // Ignore. Mangle::ASTMangler NewMangler; return NewMangler.mangleLocalTypeDecl(D); } bool ide::printModuleUSR(ModuleEntity Mod, raw_ostream &OS) { if (auto *D = Mod.getAsSwiftModule()) { StringRef moduleName = D->getName().str(); return clang::index::generateFullUSRForTopLevelModuleName(moduleName, OS); } else if (auto ClangM = Mod.getAsClangModule()) { return clang::index::generateFullUSRForModule(ClangM, OS); } else { return true; } } bool ide::printValueDeclUSR(const ValueDecl *D, raw_ostream &OS) { auto result = evaluateOrDefault(D->getASTContext().evaluator, USRGenerationRequest { D }, std::string()); if (result.empty()) return true; OS << result; return false; } bool ide::printAccessorUSR(const AbstractStorageDecl *D, AccessorKind AccKind, llvm::raw_ostream &OS) { // AccKind should always be either IsGetter or IsSetter here, based // on whether a reference is a mutating or non-mutating use. USRs // aren't supposed to reflect implementation differences like stored // vs. addressed vs. observing. // // On the other side, the implementation indexer should be // registering the getter/setter USRs independently of how they're // actually implemented. So a stored variable should still have // getter/setter USRs (pointing to the variable declaration), and an // addressed variable should have its "getter" point at the // addressor. AbstractStorageDecl *SD = const_cast<AbstractStorageDecl*>(D); if (shouldUseObjCUSR(SD)) { return printObjCUSRForAccessor(SD, AccKind, OS); } Mangle::ASTMangler NewMangler; std::string Mangled = NewMangler.mangleAccessorEntityAsUSR(AccKind, SD, getUSRSpacePrefix()); OS << Mangled; return false; } bool ide::printExtensionUSR(const ExtensionDecl *ED, raw_ostream &OS) { auto nominal = ED->getExtendedNominal(); if (!nominal) return true; // We make up a unique usr for each extension by combining a prefix // and the USR of the first value member of the extension. for (auto D : ED->getMembers()) { if (auto VD = dyn_cast<ValueDecl>(D)) { OS << getUSRSpacePrefix() << "e:"; return printValueDeclUSR(VD, OS); } } OS << getUSRSpacePrefix() << "e:"; printValueDeclUSR(nominal, OS); for (auto Inherit : ED->getInherited()) { if (auto T = Inherit.getType()) { if (T->getAnyNominal()) return printValueDeclUSR(T->getAnyNominal(), OS); } } return true; } bool ide::printDeclUSR(const Decl *D, raw_ostream &OS) { if (D->isImplicit()) return true; if (auto *VD = dyn_cast<ValueDecl>(D)) { if (ide::printValueDeclUSR(VD, OS)) { return true; } } else if (auto *ED = dyn_cast<ExtensionDecl>(D)) { if (ide::printExtensionUSR(ED, OS)) { return true; } } else { return true; } return false; } <commit_msg>AST: Stop checking hasInterfaceType() in MangleLocalTypeDeclRequest<commit_after>//===--- USRGeneration.cpp - Routines for USR generation ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/AST/ASTContext.h" #include "swift/AST/ClangModuleLoader.h" #include "swift/AST/Module.h" #include "swift/AST/USRGeneration.h" #include "swift/AST/ASTMangler.h" #include "swift/AST/SwiftNameTranslation.h" #include "swift/AST/TypeCheckRequests.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/raw_ostream.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Attr.h" #include "clang/Index/USRGeneration.h" #include "clang/Lex/PreprocessingRecord.h" #include "clang/Lex/Preprocessor.h" using namespace swift; using namespace ide; static inline StringRef getUSRSpacePrefix() { return "s:"; } bool ide::printTypeUSR(Type Ty, raw_ostream &OS) { assert(!Ty->hasArchetype() && "cannot have contextless archetypes mangled."); Mangle::ASTMangler Mangler; OS << Mangler.mangleTypeAsUSR(Ty->getRValueType()); return false; } bool ide::printDeclTypeUSR(const ValueDecl *D, raw_ostream &OS) { Mangle::ASTMangler Mangler; std::string MangledName = Mangler.mangleDeclType(D); OS << MangledName; return false; } static bool printObjCUSRFragment(const ValueDecl *D, StringRef ObjCName, const ExtensionDecl *ExtContextD, raw_ostream &OS) { if (!D) return true; // The Swift module name that the decl originated from. If the decl is // originating from ObjC code (ObjC module or the bridging header) then this // will be empty. StringRef ModuleName; if (!D->hasClangNode()) ModuleName = D->getModuleContext()->getNameStr(); if (isa<ClassDecl>(D)) { StringRef extContextName; if (ExtContextD) { extContextName = ExtContextD->getModuleContext()->getNameStr(); } clang::index::generateUSRForObjCClass(ObjCName, OS, ModuleName, extContextName); } else if (isa<ProtocolDecl>(D)) { clang::index::generateUSRForObjCProtocol(ObjCName, OS, ModuleName); } else if (isa<VarDecl>(D)) { clang::index::generateUSRForObjCProperty(ObjCName, D->isStatic(), OS); } else if (isa<ConstructorDecl>(D)) { // init() is a class member in Swift, but an instance method in ObjC. clang::index::generateUSRForObjCMethod(ObjCName, /*IsInstanceMethod=*/true, OS); } else if (isa<AbstractFunctionDecl>(D)) { clang::index::generateUSRForObjCMethod(ObjCName, D->isInstanceMember(), OS); } else if (isa<EnumDecl>(D)) { clang::index::generateUSRForGlobalEnum(ObjCName, OS, ModuleName); } else if (isa<EnumElementDecl>(D)) { clang::index::generateUSRForEnumConstant(ObjCName, OS); } else { llvm_unreachable("Unexpected value decl"); } return false; } static bool printObjCUSRContext(const Decl *D, raw_ostream &OS) { OS << clang::index::getUSRSpacePrefix(); auto *DC = D->getDeclContext(); if (auto *Parent = DC->getSelfNominalTypeDecl()) { auto *extContextD = dyn_cast<ExtensionDecl>(DC); auto ObjCName = objc_translation::getObjCNameForSwiftDecl(Parent); if (printObjCUSRFragment(Parent, ObjCName.first.str(), extContextD, OS)) return true; } return false; } static bool printObjCUSRForAccessor(const AbstractStorageDecl *ASD, AccessorKind Kind, raw_ostream &OS) { if (printObjCUSRContext(ASD, OS)) return true; ObjCSelector Selector; switch (Kind) { case swift::AccessorKind::Get: Selector = ASD->getObjCGetterSelector(); break; case swift::AccessorKind::Set: Selector = ASD->getObjCSetterSelector(); break; default: llvm_unreachable("invalid accessor kind"); } assert(Selector); llvm::SmallString<128> Buf; clang::index::generateUSRForObjCMethod(Selector.getString(Buf), ASD->isInstanceMember(), OS); return false; } static bool printObjCUSR(const ValueDecl *D, raw_ostream &OS) { if (printObjCUSRContext(D, OS)) return true; auto *extContextD = dyn_cast<ExtensionDecl>(D->getDeclContext()); auto ObjCName = objc_translation::getObjCNameForSwiftDecl(D); if (!ObjCName.first.empty()) return printObjCUSRFragment(D, ObjCName.first.str(), extContextD, OS); assert(ObjCName.second); llvm::SmallString<128> Buf; return printObjCUSRFragment(D, ObjCName.second.getString(Buf), extContextD, OS); } static bool shouldUseObjCUSR(const Decl *D) { // Only the subscript getter/setter are visible to ObjC rather than the // subscript itself if (isa<SubscriptDecl>(D)) return false; auto Parent = D->getDeclContext()->getInnermostDeclarationDeclContext(); if (Parent && (!shouldUseObjCUSR(Parent) || // parent should be visible too !D->getDeclContext()->isTypeContext() || // no local decls isa<TypeDecl>(D))) // nested types aren't supported return false; if (const auto *VD = dyn_cast<ValueDecl>(D)) { if (isa<EnumElementDecl>(VD)) return true; return objc_translation::isVisibleToObjC(VD, AccessLevel::Internal); } if (const auto *ED = dyn_cast<ExtensionDecl>(D)) { if (auto baseClass = ED->getSelfClassDecl()) { return shouldUseObjCUSR(baseClass) && !baseClass->isForeign(); } } return false; } llvm::Expected<std::string> swift::USRGenerationRequest::evaluate(Evaluator &evaluator, const ValueDecl *D) const { if (auto *VD = dyn_cast<VarDecl>(D)) D = VD->getCanonicalVarDecl(); if (!D->hasName() && !isa<ParamDecl>(D) && !isa<AccessorDecl>(D)) return std::string(); // Ignore. if (D->getModuleContext()->isBuiltinModule()) return std::string(); // Ignore. if (isa<ModuleDecl>(D)) return std::string(); // Ignore. auto interpretAsClangNode = [](const ValueDecl *D)->ClangNode { ClangNode ClangN = D->getClangNode(); if (auto ClangD = ClangN.getAsDecl()) { // NSErrorDomain causes the clang enum to be imported like this: // // struct MyError { // enum Code : Int32 { // case errFirst // case errSecond // } // static var errFirst: MyError.Code { get } // static var errSecond: MyError.Code { get } // } // // The clang enum constants are associated with both the static vars and // the enum cases. // But we want unique USRs for the above symbols, so use the clang USR // for the enum cases, and the Swift USR for the vars. // if (auto *ClangEnumConst = dyn_cast<clang::EnumConstantDecl>(ClangD)) { if (auto *ClangEnum = dyn_cast<clang::EnumDecl>(ClangEnumConst->getDeclContext())) { if (ClangEnum->hasAttr<clang::NSErrorDomainAttr>() && isa<VarDecl>(D)) return ClangNode(); } } } return ClangN; }; llvm::SmallString<128> Buffer; llvm::raw_svector_ostream OS(Buffer); if (ClangNode ClangN = interpretAsClangNode(D)) { if (auto ClangD = ClangN.getAsDecl()) { bool Ignore = clang::index::generateUSRForDecl(ClangD, Buffer); if (!Ignore) { return Buffer.str(); } else { return std::string(); } } auto &Importer = *D->getASTContext().getClangModuleLoader(); auto ClangMacroInfo = ClangN.getAsMacro(); bool Ignore = clang::index::generateUSRForMacro( D->getBaseName().getIdentifier().str(), ClangMacroInfo->getDefinitionLoc(), Importer.getClangASTContext().getSourceManager(), Buffer); if (!Ignore) return Buffer.str(); else return std::string(); } if (shouldUseObjCUSR(D)) { if (printObjCUSR(D, OS)) { return std::string(); } else { return OS.str(); } } auto declIFaceTy = D->getInterfaceType(); if (!declIFaceTy) return std::string(); // Invalid code. if (declIFaceTy.findIf([](Type t) -> bool { return t->is<ModuleType>(); })) return std::string(); Mangle::ASTMangler NewMangler; return NewMangler.mangleDeclAsUSR(D, getUSRSpacePrefix()); } llvm::Expected<std::string> swift::MangleLocalTypeDeclRequest::evaluate(Evaluator &evaluator, const TypeDecl *D) const { if (!D->getInterfaceType()) return std::string(); if (isa<ModuleDecl>(D)) return std::string(); // Ignore. Mangle::ASTMangler NewMangler; return NewMangler.mangleLocalTypeDecl(D); } bool ide::printModuleUSR(ModuleEntity Mod, raw_ostream &OS) { if (auto *D = Mod.getAsSwiftModule()) { StringRef moduleName = D->getName().str(); return clang::index::generateFullUSRForTopLevelModuleName(moduleName, OS); } else if (auto ClangM = Mod.getAsClangModule()) { return clang::index::generateFullUSRForModule(ClangM, OS); } else { return true; } } bool ide::printValueDeclUSR(const ValueDecl *D, raw_ostream &OS) { auto result = evaluateOrDefault(D->getASTContext().evaluator, USRGenerationRequest { D }, std::string()); if (result.empty()) return true; OS << result; return false; } bool ide::printAccessorUSR(const AbstractStorageDecl *D, AccessorKind AccKind, llvm::raw_ostream &OS) { // AccKind should always be either IsGetter or IsSetter here, based // on whether a reference is a mutating or non-mutating use. USRs // aren't supposed to reflect implementation differences like stored // vs. addressed vs. observing. // // On the other side, the implementation indexer should be // registering the getter/setter USRs independently of how they're // actually implemented. So a stored variable should still have // getter/setter USRs (pointing to the variable declaration), and an // addressed variable should have its "getter" point at the // addressor. AbstractStorageDecl *SD = const_cast<AbstractStorageDecl*>(D); if (shouldUseObjCUSR(SD)) { return printObjCUSRForAccessor(SD, AccKind, OS); } Mangle::ASTMangler NewMangler; std::string Mangled = NewMangler.mangleAccessorEntityAsUSR(AccKind, SD, getUSRSpacePrefix()); OS << Mangled; return false; } bool ide::printExtensionUSR(const ExtensionDecl *ED, raw_ostream &OS) { auto nominal = ED->getExtendedNominal(); if (!nominal) return true; // We make up a unique usr for each extension by combining a prefix // and the USR of the first value member of the extension. for (auto D : ED->getMembers()) { if (auto VD = dyn_cast<ValueDecl>(D)) { OS << getUSRSpacePrefix() << "e:"; return printValueDeclUSR(VD, OS); } } OS << getUSRSpacePrefix() << "e:"; printValueDeclUSR(nominal, OS); for (auto Inherit : ED->getInherited()) { if (auto T = Inherit.getType()) { if (T->getAnyNominal()) return printValueDeclUSR(T->getAnyNominal(), OS); } } return true; } bool ide::printDeclUSR(const Decl *D, raw_ostream &OS) { if (D->isImplicit()) return true; if (auto *VD = dyn_cast<ValueDecl>(D)) { if (ide::printValueDeclUSR(VD, OS)) { return true; } } else if (auto *ED = dyn_cast<ExtensionDecl>(D)) { if (ide::printExtensionUSR(ED, OS)) { return true; } } else { return true; } return false; } <|endoftext|>
<commit_before>///===--- FileManager.cpp - File System Probing and Caching ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the FileManager interface. // //===----------------------------------------------------------------------===// // // TODO: This should index all interesting directories with dirent calls. // getdirentries ? // opendir/readdir_r/closedir ? // //===----------------------------------------------------------------------===// #include "clang/Basic/FileManager.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Path.h" #include "llvm/Config/config.h" #include <map> #include <set> #include <string> using namespace clang; // FIXME: Enhance libsystem to support inode and other fields. #include <sys/stat.h> #if defined(_MSC_VER) #define S_ISDIR(s) (_S_IFDIR & s) #endif /// NON_EXISTENT_DIR - A special value distinct from null that is used to /// represent a dir name that doesn't exist on the disk. #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1) //===----------------------------------------------------------------------===// // Windows. //===----------------------------------------------------------------------===// #ifdef LLVM_ON_WIN32 #define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/' || (x) == '\\') namespace { static std::string GetFullPath(const char *relPath) { char *absPathStrPtr = _fullpath(NULL, relPath, 0); assert(absPathStrPtr && "_fullpath() returned NULL!"); std::string absPath(absPathStrPtr); free(absPathStrPtr); return absPath; } } class FileManager::UniqueDirContainer { /// UniqueDirs - Cache from full path to existing directories/files. /// llvm::StringMap<DirectoryEntry> UniqueDirs; public: DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) { std::string FullPath(GetFullPath(Name)); return UniqueDirs.GetOrCreateValue( FullPath.c_str(), FullPath.c_str() + FullPath.size() ).getValue(); } size_t size() { return UniqueDirs.size(); } }; class FileManager::UniqueFileContainer { /// UniqueFiles - Cache from full path to existing directories/files. /// llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles; public: FileEntry &getFile(const char *Name, struct stat &StatBuf) { std::string FullPath(GetFullPath(Name)); return UniqueFiles.GetOrCreateValue( FullPath.c_str(), FullPath.c_str() + FullPath.size() ).getValue(); } size_t size() { return UniqueFiles.size(); } }; //===----------------------------------------------------------------------===// // Unix-like Systems. //===----------------------------------------------------------------------===// #else #define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/') class FileManager::UniqueDirContainer { /// UniqueDirs - Cache from ID's to existing directories/files. /// std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs; public: DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) { return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)]; } size_t size() { return UniqueDirs.size(); } }; class FileManager::UniqueFileContainer { /// UniqueFiles - Cache from ID's to existing directories/files. /// std::set<FileEntry> UniqueFiles; public: FileEntry &getFile(const char *Name, struct stat &StatBuf) { return const_cast<FileEntry&>( *UniqueFiles.insert(FileEntry(StatBuf.st_dev, StatBuf.st_ino, StatBuf.st_mode)).first); } size_t size() { return UniqueFiles.size(); } }; #endif //===----------------------------------------------------------------------===// // Common logic. //===----------------------------------------------------------------------===// FileManager::FileManager() : UniqueDirs(*new UniqueDirContainer), UniqueFiles(*new UniqueFileContainer), DirEntries(64), FileEntries(64), NextFileUID(0) { NumDirLookups = NumFileLookups = 0; NumDirCacheMisses = NumFileCacheMisses = 0; } FileManager::~FileManager() { delete &UniqueDirs; delete &UniqueFiles; for (llvm::SmallVectorImpl<FileEntry *>::iterator V = VirtualFileEntries.begin(), VEnd = VirtualFileEntries.end(); V != VEnd; ++V) delete *V; } void FileManager::addStatCache(StatSysCallCache *statCache, bool AtBeginning) { assert(statCache && "No stat cache provided?"); if (AtBeginning || StatCache.get() == 0) { statCache->setNextStatCache(StatCache.take()); StatCache.reset(statCache); return; } StatSysCallCache *LastCache = StatCache.get(); while (LastCache->getNextStatCache()) LastCache = LastCache->getNextStatCache(); LastCache->setNextStatCache(statCache); } void FileManager::removeStatCache(StatSysCallCache *statCache) { if (!statCache) return; if (StatCache.get() == statCache) { // This is the first stat cache. StatCache.reset(StatCache->takeNextStatCache()); return; } // Find the stat cache in the list. StatSysCallCache *PrevCache = StatCache.get(); while (PrevCache && PrevCache->getNextStatCache() != statCache) PrevCache = PrevCache->getNextStatCache(); if (PrevCache) PrevCache->setNextStatCache(statCache->getNextStatCache()); else assert(false && "Stat cache not found for removal"); } /// \brief Retrieve the directory that the given file name resides in. static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr, const char *NameStart, const char *NameEnd) { // Figure out what directory it is in. If the string contains a / in it, // strip off everything after it. // FIXME: this logic should be in sys::Path. const char *SlashPos = NameEnd-1; while (SlashPos >= NameStart && !IS_DIR_SEPARATOR_CHAR(SlashPos[0])) --SlashPos; // Ignore duplicate //'s. while (SlashPos > NameStart && IS_DIR_SEPARATOR_CHAR(SlashPos[-1])) --SlashPos; if (SlashPos < NameStart) { // Use the current directory if file has no path component. const char *Name = "."; return FileMgr.getDirectory(Name, Name+1); } else if (SlashPos == NameEnd-1) return 0; // If filename ends with a /, it's a directory. else return FileMgr.getDirectory(NameStart, SlashPos); } /// getDirectory - Lookup, cache, and verify the specified directory. This /// returns null if the directory doesn't exist. /// const DirectoryEntry *FileManager::getDirectory(const char *NameStart, const char *NameEnd) { // stat doesn't like trailing separators (at least on Windows). if (((NameEnd - NameStart) > 1) && ((*(NameEnd - 1) == '/') || (*(NameEnd - 1) == '\\'))) NameEnd--; ++NumDirLookups; llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt = DirEntries.GetOrCreateValue(NameStart, NameEnd); // See if there is already an entry in the map. if (NamedDirEnt.getValue()) return NamedDirEnt.getValue() == NON_EXISTENT_DIR ? 0 : NamedDirEnt.getValue(); ++NumDirCacheMisses; // By default, initialize it to invalid. NamedDirEnt.setValue(NON_EXISTENT_DIR); // Get the null-terminated directory name as stored as the key of the // DirEntries map. const char *InterndDirName = NamedDirEnt.getKeyData(); // Check to see if the directory exists. struct stat StatBuf; if (stat_cached(InterndDirName, &StatBuf) || // Error stat'ing. !S_ISDIR(StatBuf.st_mode)) // Not a directory? return 0; // It exists. See if we have already opened a directory with the same inode. // This occurs when one dir is symlinked to another, for example. DirectoryEntry &UDE = UniqueDirs.getDirectory(InterndDirName, StatBuf); NamedDirEnt.setValue(&UDE); if (UDE.getName()) // Already have an entry with this inode, return it. return &UDE; // Otherwise, we don't have this directory yet, add it. We use the string // key from the DirEntries map as the string. UDE.Name = InterndDirName; return &UDE; } /// NON_EXISTENT_FILE - A special value distinct from null that is used to /// represent a filename that doesn't exist on the disk. #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1) /// getFile - Lookup, cache, and verify the specified file. This returns null /// if the file doesn't exist. /// const FileEntry *FileManager::getFile(const char *NameStart, const char *NameEnd) { ++NumFileLookups; // See if there is already an entry in the map. llvm::StringMapEntry<FileEntry *> &NamedFileEnt = FileEntries.GetOrCreateValue(NameStart, NameEnd); // See if there is already an entry in the map. if (NamedFileEnt.getValue()) return NamedFileEnt.getValue() == NON_EXISTENT_FILE ? 0 : NamedFileEnt.getValue(); ++NumFileCacheMisses; // By default, initialize it to invalid. NamedFileEnt.setValue(NON_EXISTENT_FILE); // Get the null-terminated file name as stored as the key of the // FileEntries map. const char *InterndFileName = NamedFileEnt.getKeyData(); const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, NameStart, NameEnd); if (DirInfo == 0) // Directory doesn't exist, file can't exist. return 0; // FIXME: Use the directory info to prune this, before doing the stat syscall. // FIXME: This will reduce the # syscalls. // Nope, there isn't. Check to see if the file exists. struct stat StatBuf; //llvm::errs() << "STATING: " << Filename; if (stat_cached(InterndFileName, &StatBuf) || // Error stat'ing. S_ISDIR(StatBuf.st_mode)) { // A directory? // If this file doesn't exist, we leave a null in FileEntries for this path. //llvm::errs() << ": Not existing\n"; return 0; } //llvm::errs() << ": exists\n"; // It exists. See if we have already opened a file with the same inode. // This occurs when one dir is symlinked to another, for example. FileEntry &UFE = UniqueFiles.getFile(InterndFileName, StatBuf); NamedFileEnt.setValue(&UFE); if (UFE.getName()) // Already have an entry with this inode, return it. return &UFE; // Otherwise, we don't have this directory yet, add it. // FIXME: Change the name to be a char* that points back to the 'FileEntries' // key. UFE.Name = InterndFileName; UFE.Size = StatBuf.st_size; UFE.ModTime = StatBuf.st_mtime; UFE.Dir = DirInfo; UFE.UID = NextFileUID++; return &UFE; } const FileEntry * FileManager::getVirtualFile(llvm::StringRef Filename, off_t Size, time_t ModificationTime) { const char *NameStart = Filename.begin(), *NameEnd = Filename.end(); ++NumFileLookups; // See if there is already an entry in the map. llvm::StringMapEntry<FileEntry *> &NamedFileEnt = FileEntries.GetOrCreateValue(NameStart, NameEnd); // See if there is already an entry in the map. if (NamedFileEnt.getValue()) return NamedFileEnt.getValue() == NON_EXISTENT_FILE ? 0 : NamedFileEnt.getValue(); ++NumFileCacheMisses; // By default, initialize it to invalid. NamedFileEnt.setValue(NON_EXISTENT_FILE); const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, NameStart, NameEnd); if (DirInfo == 0) // Directory doesn't exist, file can't exist. return 0; FileEntry *UFE = new FileEntry(); VirtualFileEntries.push_back(UFE); NamedFileEnt.setValue(UFE); UFE->Name = NamedFileEnt.getKeyData(); UFE->Size = Size; UFE->ModTime = ModificationTime; UFE->Dir = DirInfo; UFE->UID = NextFileUID++; // If this virtual file resolves to a file, also map that file to the // newly-created file entry. const char *InterndFileName = NamedFileEnt.getKeyData(); struct stat StatBuf; if (!stat_cached(InterndFileName, &StatBuf) && !S_ISDIR(StatBuf.st_mode)) { llvm::sys::Path FilePath(InterndFileName); FilePath.makeAbsolute(); FileEntries[FilePath.str()] = UFE; } return UFE; } void FileManager::PrintStats() const { llvm::errs() << "\n*** File Manager Stats:\n"; llvm::errs() << UniqueFiles.size() << " files found, " << UniqueDirs.size() << " dirs found.\n"; llvm::errs() << NumDirLookups << " dir lookups, " << NumDirCacheMisses << " dir cache misses.\n"; llvm::errs() << NumFileLookups << " file lookups, " << NumFileCacheMisses << " file cache misses.\n"; //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups; } int MemorizeStatCalls::stat(const char *path, struct stat *buf) { int result = StatSysCallCache::stat(path, buf); // Do not cache failed stats, it is easy to construct common inconsistent // situations if we do, and they are not important for PCH performance (which // currently only needs the stats to construct the initial FileManager // entries). if (result != 0) return result; // Cache file 'stat' results and directories with absolutely paths. if (!S_ISDIR(buf->st_mode) || llvm::sys::Path(path).isAbsolute()) StatCalls[path] = StatResult(result, *buf); return result; } <commit_msg>fix PR7953 - Windows filename are case insensitive:<commit_after>///===--- FileManager.cpp - File System Probing and Caching ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the FileManager interface. // //===----------------------------------------------------------------------===// // // TODO: This should index all interesting directories with dirent calls. // getdirentries ? // opendir/readdir_r/closedir ? // //===----------------------------------------------------------------------===// #include "clang/Basic/FileManager.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Path.h" #include "llvm/Config/config.h" #include <map> #include <set> #include <string> using namespace clang; // FIXME: Enhance libsystem to support inode and other fields. #include <sys/stat.h> #if defined(_MSC_VER) #define S_ISDIR(s) (_S_IFDIR & s) #endif /// NON_EXISTENT_DIR - A special value distinct from null that is used to /// represent a dir name that doesn't exist on the disk. #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1) //===----------------------------------------------------------------------===// // Windows. //===----------------------------------------------------------------------===// #ifdef LLVM_ON_WIN32 #define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/' || (x) == '\\') namespace { static std::string GetFullPath(const char *relPath) { char *absPathStrPtr = _fullpath(NULL, relPath, 0); assert(absPathStrPtr && "_fullpath() returned NULL!"); std::string absPath(absPathStrPtr); free(absPathStrPtr); return absPath; } } class FileManager::UniqueDirContainer { /// UniqueDirs - Cache from full path to existing directories/files. /// llvm::StringMap<DirectoryEntry> UniqueDirs; public: DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) { std::string FullPath(GetFullPath(Name)); return UniqueDirs.GetOrCreateValue( FullPath.c_str(), FullPath.c_str() + FullPath.size() ).getValue(); } size_t size() { return UniqueDirs.size(); } }; class FileManager::UniqueFileContainer { /// UniqueFiles - Cache from full path to existing directories/files. /// llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles; public: FileEntry &getFile(const char *Name, struct stat &StatBuf) { std::string FullPath(GetFullPath(Name)); // LowercaseString because Windows filesystem is case insensitive. FullPath = llvm::LowercaseString(FullPath); return UniqueFiles.GetOrCreateValue( FullPath.c_str(), FullPath.c_str() + FullPath.size() ).getValue(); } size_t size() { return UniqueFiles.size(); } }; //===----------------------------------------------------------------------===// // Unix-like Systems. //===----------------------------------------------------------------------===// #else #define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/') class FileManager::UniqueDirContainer { /// UniqueDirs - Cache from ID's to existing directories/files. /// std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs; public: DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) { return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)]; } size_t size() { return UniqueDirs.size(); } }; class FileManager::UniqueFileContainer { /// UniqueFiles - Cache from ID's to existing directories/files. /// std::set<FileEntry> UniqueFiles; public: FileEntry &getFile(const char *Name, struct stat &StatBuf) { return const_cast<FileEntry&>( *UniqueFiles.insert(FileEntry(StatBuf.st_dev, StatBuf.st_ino, StatBuf.st_mode)).first); } size_t size() { return UniqueFiles.size(); } }; #endif //===----------------------------------------------------------------------===// // Common logic. //===----------------------------------------------------------------------===// FileManager::FileManager() : UniqueDirs(*new UniqueDirContainer), UniqueFiles(*new UniqueFileContainer), DirEntries(64), FileEntries(64), NextFileUID(0) { NumDirLookups = NumFileLookups = 0; NumDirCacheMisses = NumFileCacheMisses = 0; } FileManager::~FileManager() { delete &UniqueDirs; delete &UniqueFiles; for (llvm::SmallVectorImpl<FileEntry *>::iterator V = VirtualFileEntries.begin(), VEnd = VirtualFileEntries.end(); V != VEnd; ++V) delete *V; } void FileManager::addStatCache(StatSysCallCache *statCache, bool AtBeginning) { assert(statCache && "No stat cache provided?"); if (AtBeginning || StatCache.get() == 0) { statCache->setNextStatCache(StatCache.take()); StatCache.reset(statCache); return; } StatSysCallCache *LastCache = StatCache.get(); while (LastCache->getNextStatCache()) LastCache = LastCache->getNextStatCache(); LastCache->setNextStatCache(statCache); } void FileManager::removeStatCache(StatSysCallCache *statCache) { if (!statCache) return; if (StatCache.get() == statCache) { // This is the first stat cache. StatCache.reset(StatCache->takeNextStatCache()); return; } // Find the stat cache in the list. StatSysCallCache *PrevCache = StatCache.get(); while (PrevCache && PrevCache->getNextStatCache() != statCache) PrevCache = PrevCache->getNextStatCache(); if (PrevCache) PrevCache->setNextStatCache(statCache->getNextStatCache()); else assert(false && "Stat cache not found for removal"); } /// \brief Retrieve the directory that the given file name resides in. static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr, const char *NameStart, const char *NameEnd) { // Figure out what directory it is in. If the string contains a / in it, // strip off everything after it. // FIXME: this logic should be in sys::Path. const char *SlashPos = NameEnd-1; while (SlashPos >= NameStart && !IS_DIR_SEPARATOR_CHAR(SlashPos[0])) --SlashPos; // Ignore duplicate //'s. while (SlashPos > NameStart && IS_DIR_SEPARATOR_CHAR(SlashPos[-1])) --SlashPos; if (SlashPos < NameStart) { // Use the current directory if file has no path component. const char *Name = "."; return FileMgr.getDirectory(Name, Name+1); } else if (SlashPos == NameEnd-1) return 0; // If filename ends with a /, it's a directory. else return FileMgr.getDirectory(NameStart, SlashPos); } /// getDirectory - Lookup, cache, and verify the specified directory. This /// returns null if the directory doesn't exist. /// const DirectoryEntry *FileManager::getDirectory(const char *NameStart, const char *NameEnd) { // stat doesn't like trailing separators (at least on Windows). if (((NameEnd - NameStart) > 1) && ((*(NameEnd - 1) == '/') || (*(NameEnd - 1) == '\\'))) NameEnd--; ++NumDirLookups; llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt = DirEntries.GetOrCreateValue(NameStart, NameEnd); // See if there is already an entry in the map. if (NamedDirEnt.getValue()) return NamedDirEnt.getValue() == NON_EXISTENT_DIR ? 0 : NamedDirEnt.getValue(); ++NumDirCacheMisses; // By default, initialize it to invalid. NamedDirEnt.setValue(NON_EXISTENT_DIR); // Get the null-terminated directory name as stored as the key of the // DirEntries map. const char *InterndDirName = NamedDirEnt.getKeyData(); // Check to see if the directory exists. struct stat StatBuf; if (stat_cached(InterndDirName, &StatBuf) || // Error stat'ing. !S_ISDIR(StatBuf.st_mode)) // Not a directory? return 0; // It exists. See if we have already opened a directory with the same inode. // This occurs when one dir is symlinked to another, for example. DirectoryEntry &UDE = UniqueDirs.getDirectory(InterndDirName, StatBuf); NamedDirEnt.setValue(&UDE); if (UDE.getName()) // Already have an entry with this inode, return it. return &UDE; // Otherwise, we don't have this directory yet, add it. We use the string // key from the DirEntries map as the string. UDE.Name = InterndDirName; return &UDE; } /// NON_EXISTENT_FILE - A special value distinct from null that is used to /// represent a filename that doesn't exist on the disk. #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1) /// getFile - Lookup, cache, and verify the specified file. This returns null /// if the file doesn't exist. /// const FileEntry *FileManager::getFile(const char *NameStart, const char *NameEnd) { ++NumFileLookups; // See if there is already an entry in the map. llvm::StringMapEntry<FileEntry *> &NamedFileEnt = FileEntries.GetOrCreateValue(NameStart, NameEnd); // See if there is already an entry in the map. if (NamedFileEnt.getValue()) return NamedFileEnt.getValue() == NON_EXISTENT_FILE ? 0 : NamedFileEnt.getValue(); ++NumFileCacheMisses; // By default, initialize it to invalid. NamedFileEnt.setValue(NON_EXISTENT_FILE); // Get the null-terminated file name as stored as the key of the // FileEntries map. const char *InterndFileName = NamedFileEnt.getKeyData(); const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, NameStart, NameEnd); if (DirInfo == 0) // Directory doesn't exist, file can't exist. return 0; // FIXME: Use the directory info to prune this, before doing the stat syscall. // FIXME: This will reduce the # syscalls. // Nope, there isn't. Check to see if the file exists. struct stat StatBuf; //llvm::errs() << "STATING: " << Filename; if (stat_cached(InterndFileName, &StatBuf) || // Error stat'ing. S_ISDIR(StatBuf.st_mode)) { // A directory? // If this file doesn't exist, we leave a null in FileEntries for this path. //llvm::errs() << ": Not existing\n"; return 0; } //llvm::errs() << ": exists\n"; // It exists. See if we have already opened a file with the same inode. // This occurs when one dir is symlinked to another, for example. FileEntry &UFE = UniqueFiles.getFile(InterndFileName, StatBuf); NamedFileEnt.setValue(&UFE); if (UFE.getName()) // Already have an entry with this inode, return it. return &UFE; // Otherwise, we don't have this directory yet, add it. // FIXME: Change the name to be a char* that points back to the 'FileEntries' // key. UFE.Name = InterndFileName; UFE.Size = StatBuf.st_size; UFE.ModTime = StatBuf.st_mtime; UFE.Dir = DirInfo; UFE.UID = NextFileUID++; return &UFE; } const FileEntry * FileManager::getVirtualFile(llvm::StringRef Filename, off_t Size, time_t ModificationTime) { const char *NameStart = Filename.begin(), *NameEnd = Filename.end(); ++NumFileLookups; // See if there is already an entry in the map. llvm::StringMapEntry<FileEntry *> &NamedFileEnt = FileEntries.GetOrCreateValue(NameStart, NameEnd); // See if there is already an entry in the map. if (NamedFileEnt.getValue()) return NamedFileEnt.getValue() == NON_EXISTENT_FILE ? 0 : NamedFileEnt.getValue(); ++NumFileCacheMisses; // By default, initialize it to invalid. NamedFileEnt.setValue(NON_EXISTENT_FILE); const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, NameStart, NameEnd); if (DirInfo == 0) // Directory doesn't exist, file can't exist. return 0; FileEntry *UFE = new FileEntry(); VirtualFileEntries.push_back(UFE); NamedFileEnt.setValue(UFE); UFE->Name = NamedFileEnt.getKeyData(); UFE->Size = Size; UFE->ModTime = ModificationTime; UFE->Dir = DirInfo; UFE->UID = NextFileUID++; // If this virtual file resolves to a file, also map that file to the // newly-created file entry. const char *InterndFileName = NamedFileEnt.getKeyData(); struct stat StatBuf; if (!stat_cached(InterndFileName, &StatBuf) && !S_ISDIR(StatBuf.st_mode)) { llvm::sys::Path FilePath(InterndFileName); FilePath.makeAbsolute(); FileEntries[FilePath.str()] = UFE; } return UFE; } void FileManager::PrintStats() const { llvm::errs() << "\n*** File Manager Stats:\n"; llvm::errs() << UniqueFiles.size() << " files found, " << UniqueDirs.size() << " dirs found.\n"; llvm::errs() << NumDirLookups << " dir lookups, " << NumDirCacheMisses << " dir cache misses.\n"; llvm::errs() << NumFileLookups << " file lookups, " << NumFileCacheMisses << " file cache misses.\n"; //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups; } int MemorizeStatCalls::stat(const char *path, struct stat *buf) { int result = StatSysCallCache::stat(path, buf); // Do not cache failed stats, it is easy to construct common inconsistent // situations if we do, and they are not important for PCH performance (which // currently only needs the stats to construct the initial FileManager // entries). if (result != 0) return result; // Cache file 'stat' results and directories with absolutely paths. if (!S_ISDIR(buf->st_mode) || llvm::sys::Path(path).isAbsolute()) StatCalls[path] = StatResult(result, *buf); return result; } <|endoftext|>
<commit_before>//===--- ARC.cpp - Implement ARC target feature support -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements ARC TargetInfo objects. // //===----------------------------------------------------------------------===// #include "ARC.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/MacroBuilder.h" #include "clang/Basic/TargetBuiltins.h" using namespace clang; using namespace clang::targets; void ARCTargetInfo::getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const { Builder.defineMacro("__arc__"); } <commit_msg>Convert two more files that were using Windows line endings and remove a stray single '\r' from one file. These are the last line ending issues I can find in the files containing parts of LLVM's file headers.<commit_after>//===--- ARC.cpp - Implement ARC target feature support -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements ARC TargetInfo objects. // //===----------------------------------------------------------------------===// #include "ARC.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/MacroBuilder.h" #include "clang/Basic/TargetBuiltins.h" using namespace clang; using namespace clang::targets; void ARCTargetInfo::getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const { Builder.defineMacro("__arc__"); } <|endoftext|>
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* Copyright (c) 2008 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld 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 "flusspferd/importer.hpp" #include "flusspferd/create.hpp" #include "flusspferd/string.hpp" #include "flusspferd/tracer.hpp" #include <boost/filesystem.hpp> #include <boost/unordered_map.hpp> #include <iostream> #include <fstream> #include <string> #include <sstream> #include <errno.h> // Wrap the windows calls to the *nix equivalents #ifndef _WIN32 #include <dlfcn.h> #define DIRSEP1 "/" #define DIRSEP2 "" #define SHLIBPREFIX "lib" #ifdef APPLE #define SHLIBSUFFIX ".dylib" #else #define SHLIBSUFFIX ".so" #endif #else #include <windows.h> #define DIRSEP1 "\\" #define DIRSEP2 "/" #define SHLIBPREFIX 0 #define SHLIBSUFFIX ".dll" #define dlopen(x,y) (void*)LoadLibrary(x) #define dlsym(x,y) (void*)GetProcAddress((HMODULE)x,y) #define dlclose(x) FreeLibrary((HMODULE)x) // FIXME - not thread safe? const char *dlerror() { static char szMsgBuf[256]; ::FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, ::GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), szMsgBuf, sizeof szMsgBuf, NULL); return szMsgBuf; } #endif using namespace flusspferd; object importer::class_info::create_prototype() { object proto = create_object(); return proto; } void importer::class_info::augment_constructor(object &ctor) { ctor.define_property("preload", create_object()); ctor.define_property("defaultPaths", create_array(), read_only_property); create_native_function(ctor, "lockPaths", &importer::lock_paths); } void importer::lock_paths(object &ctor) { ctor.define_property("pathsLocked", true, read_only_property); //TODO: seal defaultPaths } class importer::impl { public: typedef std::pair<std::string, bool> key_type; typedef boost::unordered_map<key_type, value> module_cache_map; module_cache_map module_cache; }; importer::importer(object const &obj, call_context &) : native_object_base(obj), p(new impl) { // Create the load method on the actual object itself, not on the prototype // That way the following works: // // i.load('foo'); // Assume foo module defines this.foo = 'abc' // print(i.foo); // abc // // without the problem of load being overridden to do bad things add_native_method("load", 2); register_native_method("load", &importer::load); context ctx = get_current_context(); object constructor = ctx.get_constructor<importer>(); // Store search paths array arr = constructor.get_property("defaultPaths").to_object(); set_property("paths", arr.call("concat")); //TODO seal if necessaey // Create a context object, which is the object on which all modules are // evaluated object context = create_object(); set_property("context", context); // this.contexnt.__proto__ = this.__proto__; // Not sure we actually want to do this, but we can for now. context.set_prototype(get_prototype()); set_prototype(context); } importer::~importer() {} void importer::trace(tracer &trc) { for (impl::module_cache_map::iterator it = p->module_cache.begin(); it != p->module_cache.end(); ++it) trc("module-cache-item", it->second); } value importer::load(string const &name, bool binary_only) { impl::key_type key(name.to_string(), binary_only); impl::module_cache_map::iterator it = p->module_cache.find(key); if (it != p->module_cache.end()) return it->second; context ctx = get_current_context(); object constructor = ctx.get_constructor<importer>(); value preload = constructor.get_property("preload"); if (preload.is_object()) { value loader = preload.get_object().get_property(name); if (loader.is_object()) { value result; if (!loader.is_null()) { local_root_scope scope; result = loader.get_object().apply(get_property("context").to_object()); } return result; } } std::string so_name, js_name; so_name = process_name(name); js_name = process_name(name, true); //TODO: I'd like a version that throws an exception instead of assert traps value paths_v = get_property("paths").to_object(); if (!paths_v.is_object()) throw exception("Unable to get search paths or its not an object"); array paths = paths_v.get_object(); // TODO: We could probably do with an array class. size_t len = paths.get_length(); for (size_t i=0; i < len; i++) { std::string path = paths.get_element(i).to_string().to_string(); std::string fullpath = path + js_name; if (!binary_only) { std::ifstream file(fullpath.c_str(), std::ios::in | std::ios::binary); if (file.good()) { // Slurp in the file std::stringstream cbuf; cbuf << file.rdbuf(); if (!file) // TODO: Is the information (fullpath) leak bad? throw exception( std::string("Error reading from ") + fullpath ); // Execute the file std::string const &contents = cbuf.str(); return get_current_context().evaluateInScope(contents.data(), contents.size(), fullpath.c_str(), 1, get_property("context").to_object()); } } fullpath = path + so_name; if (boost::filesystem::exists(fullpath)) { // Load the .so void *module = dlopen(fullpath.c_str(), RTLD_LAZY); if (!module) { std::stringstream ss; ss << "Unable to load library '" << fullpath.c_str() << "': " << dlerror(); throw exception(ss.str()); } void *symbol = dlsym(module, "flusspferd_load"); if (!symbol) { std::stringstream ss; ss << "Unable to load library '" << fullpath.c_str() << "': " << dlerror(); throw exception(ss.str()); } flusspferd_load_t func = *(flusspferd_load_t*) &symbol; return func(get_property("context").to_object()); } } // We probably want to throw an exception here. std::stringstream ss; ss << "Unable to find library '"; ss << name.c_str(); ss << "' in ["; ss << paths_v.to_string().c_str() << "]"; throw exception(ss.str()); } // Take 'foo.bar' as a flusspferd::string, check no path sep in it, and // return '/foo/bar.js' or '/foo/libbar.so', etc. as a std::string std::string importer::process_name(string const &name, bool for_script) { std::string p = name.to_string(); if (p.find(DIRSEP1, 0) != std::string::npos && p.find(DIRSEP2, 0) != std::string::npos) { throw exception("Path seperator not allowed in module name"); } unsigned int pos = 0; while ( (pos = p.find('.', pos)) != std::string::npos) { p.replace(pos, 1, DIRSEP1); pos++; } if (!for_script && SHLIBPREFIX) { // stick the lib on the front as needed pos = p.rfind(DIRSEP1, 0); if (pos == std::string::npos) pos = 0; p.insert(pos, SHLIBPREFIX); } p = DIRSEP1 + p; if (for_script) p += ".js"; else p += SHLIBSUFFIX; return p; } <commit_msg>Importer: actually seal<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* Copyright (c) 2008 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld 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 "flusspferd/importer.hpp" #include "flusspferd/create.hpp" #include "flusspferd/string.hpp" #include "flusspferd/tracer.hpp" #include <boost/filesystem.hpp> #include <boost/unordered_map.hpp> #include <iostream> #include <fstream> #include <string> #include <sstream> #include <errno.h> // Wrap the windows calls to the *nix equivalents #ifndef _WIN32 #include <dlfcn.h> #define DIRSEP1 "/" #define DIRSEP2 "" #define SHLIBPREFIX "lib" #ifdef APPLE #define SHLIBSUFFIX ".dylib" #else #define SHLIBSUFFIX ".so" #endif #else #include <windows.h> #define DIRSEP1 "\\" #define DIRSEP2 "/" #define SHLIBPREFIX 0 #define SHLIBSUFFIX ".dll" #define dlopen(x,y) (void*)LoadLibrary(x) #define dlsym(x,y) (void*)GetProcAddress((HMODULE)x,y) #define dlclose(x) FreeLibrary((HMODULE)x) // FIXME - not thread safe? const char *dlerror() { static char szMsgBuf[256]; ::FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, ::GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), szMsgBuf, sizeof szMsgBuf, NULL); return szMsgBuf; } #endif using namespace flusspferd; object importer::class_info::create_prototype() { object proto = create_object(); return proto; } void importer::class_info::augment_constructor(object &ctor) { ctor.define_property("preload", create_object()); ctor.define_property("defaultPaths", create_array(), read_only_property); create_native_function(ctor, "lockPaths", &importer::lock_paths); } void importer::lock_paths(object &ctor) { local_root_scope scope; ctor.define_property("pathsLocked", true, read_only_property); object paths = ctor.get_property("defaultPaths").to_object(); paths.seal(false); } class importer::impl { public: typedef std::pair<std::string, bool> key_type; typedef boost::unordered_map<key_type, value> module_cache_map; module_cache_map module_cache; }; importer::importer(object const &obj, call_context &) : native_object_base(obj), p(new impl) { // Create the load method on the actual object itself, not on the prototype // That way the following works: // // i.load('foo'); // Assume foo module defines this.foo = 'abc' // print(i.foo); // abc // // without the problem of load being overridden to do bad things add_native_method("load", 2); register_native_method("load", &importer::load); context ctx = get_current_context(); object constructor = ctx.get_constructor<importer>(); // Store search paths array arr = constructor.get_property("defaultPaths").to_object(); arr = arr.call("concat").to_object(); set_property("paths", arr); if (constructor.get_property("pathsLocked").to_boolean()) { arr.seal(false); } // Create a context object, which is the object on which all modules are // evaluated object context = create_object(); set_property("context", context); // this.contexnt.__proto__ = this.__proto__; // Not sure we actually want to do this, but we can for now. context.set_prototype(get_prototype()); set_prototype(context); } importer::~importer() {} void importer::trace(tracer &trc) { for (impl::module_cache_map::iterator it = p->module_cache.begin(); it != p->module_cache.end(); ++it) trc("module-cache-item", it->second); } value importer::load(string const &name, bool binary_only) { impl::key_type key(name.to_string(), binary_only); impl::module_cache_map::iterator it = p->module_cache.find(key); if (it != p->module_cache.end()) return it->second; context ctx = get_current_context(); object constructor = ctx.get_constructor<importer>(); value preload = constructor.get_property("preload"); if (preload.is_object()) { value loader = preload.get_object().get_property(name); if (loader.is_object()) { value result; if (!loader.is_null()) { local_root_scope scope; result = loader.get_object().apply(get_property("context").to_object()); } return result; } } std::string so_name, js_name; so_name = process_name(name); js_name = process_name(name, true); //TODO: I'd like a version that throws an exception instead of assert traps value paths_v = get_property("paths").to_object(); if (!paths_v.is_object()) throw exception("Unable to get search paths or its not an object"); array paths = paths_v.get_object(); // TODO: We could probably do with an array class. size_t len = paths.get_length(); for (size_t i=0; i < len; i++) { std::string path = paths.get_element(i).to_string().to_string(); std::string fullpath = path + js_name; if (!binary_only) { std::ifstream file(fullpath.c_str(), std::ios::in | std::ios::binary); if (file.good()) { // Slurp in the file std::stringstream cbuf; cbuf << file.rdbuf(); if (!file) // TODO: Is the information (fullpath) leak bad? throw exception( std::string("Error reading from ") + fullpath ); // Execute the file std::string const &contents = cbuf.str(); return get_current_context().evaluateInScope(contents.data(), contents.size(), fullpath.c_str(), 1, get_property("context").to_object()); } } fullpath = path + so_name; if (boost::filesystem::exists(fullpath)) { // Load the .so void *module = dlopen(fullpath.c_str(), RTLD_LAZY); if (!module) { std::stringstream ss; ss << "Unable to load library '" << fullpath.c_str() << "': " << dlerror(); throw exception(ss.str()); } void *symbol = dlsym(module, "flusspferd_load"); if (!symbol) { std::stringstream ss; ss << "Unable to load library '" << fullpath.c_str() << "': " << dlerror(); throw exception(ss.str()); } flusspferd_load_t func = *(flusspferd_load_t*) &symbol; return func(get_property("context").to_object()); } } // We probably want to throw an exception here. std::stringstream ss; ss << "Unable to find library '"; ss << name.c_str(); ss << "' in ["; ss << paths_v.to_string().c_str() << "]"; throw exception(ss.str()); } // Take 'foo.bar' as a flusspferd::string, check no path sep in it, and // return '/foo/bar.js' or '/foo/libbar.so', etc. as a std::string std::string importer::process_name(string const &name, bool for_script) { std::string p = name.to_string(); if (p.find(DIRSEP1, 0) != std::string::npos && p.find(DIRSEP2, 0) != std::string::npos) { throw exception("Path seperator not allowed in module name"); } unsigned int pos = 0; while ( (pos = p.find('.', pos)) != std::string::npos) { p.replace(pos, 1, DIRSEP1); pos++; } if (!for_script && SHLIBPREFIX) { // stick the lib on the front as needed pos = p.rfind(DIRSEP1, 0); if (pos == std::string::npos) pos = 0; p.insert(pos, SHLIBPREFIX); } p = DIRSEP1 + p; if (for_script) p += ".js"; else p += SHLIBSUFFIX; return p; } <|endoftext|>
<commit_before>// // File generated by c:\Devel\root_working\code\root.vc8\utils\src\rootcint_tmp.exe at Wed May 16 23:07:42 2007 // Do NOT change. Changes will be lost next time file is generated // #include "RConfig.h" #if !defined(R__ACCESS_IN_SYMBOL) //Break the privacy of classes -- Disabled for the moment #define private public #define protected public #endif // Since CINT ignores the std namespace, we need to do so in this file. namespace std {} using namespace std; #include "ManualTree2.h" #include "TClass.h" #include "TBuffer.h" #include "TMemberInspector.h" #include "TError.h" #ifndef G__ROOT #define G__ROOT #endif #include "RtypesImp.h" #include "TIsAProxy.h" // START OF SHADOWS namespace ROOT { namespace Shadow { } // of namespace Shadow } // of namespace ROOT // END OF SHADOWS /******************************************************** * tree/src/ManualTree2.cxx * CAUTION: DON'T CHANGE THIS FILE. THIS FILE IS AUTOMATICALLY GENERATED * FROM HEADER FILES LISTED IN G__setup_cpp_environmentXXX(). * CHANGE THOSE HEADER FILES AND REGENERATE THIS FILE. ********************************************************/ #ifdef G__MEMTEST #undef malloc #undef free #endif extern "C" void G__cpp_reset_tagtableManualTree2(); extern "C" void G__set_cpp_environmentManualTree2() { G__add_compiledheader("TTree.h"); G__cpp_reset_tagtableManualTree2(); } #include <new> extern "C" int G__cpp_dllrevManualTree2() { return(30051515); } /********************************************************* * Member function Interface Method *********************************************************/ /* TTree */ #include "ManualTree2Body.h" /* Setting up global function */ /********************************************************* * Member function Stub *********************************************************/ /********************************************************* * Global function Stub *********************************************************/ /********************************************************* * Get size of pointer to member function *********************************************************/ class G__Sizep2memfuncManualTree2 { public: G__Sizep2memfuncManualTree2(): p(&G__Sizep2memfuncManualTree2::sizep2memfunc) {} size_t sizep2memfunc() { return(sizeof(p)); } private: size_t (G__Sizep2memfuncManualTree2::*p)(); }; size_t G__get_sizep2memfuncManualTree2() { G__Sizep2memfuncManualTree2 a; G__setsizep2memfunc((int)a.sizep2memfunc()); return((size_t)a.sizep2memfunc()); } /********************************************************* * virtual base class offset calculation interface *********************************************************/ /* Setting up class inheritance */ /********************************************************* * Inheritance information setup/ *********************************************************/ extern "C" void G__cpp_setup_inheritanceManualTree2() { /* Setting up class inheritance */ } /********************************************************* * typedef information setup/ *********************************************************/ extern "C" void G__cpp_setup_typetableManualTree2() { /* Setting up typedef entry */ G__search_typename2("Int_t",105,-1,0,-1); G__setnewtype(-1,"Signed integer 4 bytes (int)",0); G__search_typename2("Option_t",99,-1,256,-1); G__setnewtype(-1,"Option string (const char)",0); G__search_typename2("Long64_t",110,-1,0,-1); G__setnewtype(-1,"Portable signed long integer 8 bytes",0); } /********************************************************* * Data Member information setup/ *********************************************************/ /* Setting up class,struct,union tag member variable */ extern "C" void G__cpp_setup_memvarManualTree2() { } /*********************************************************** ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ ***********************************************************/ /********************************************************* * Member function information setup for each class *********************************************************/ static void G__setup_memfuncTTree(void) { /* TTree */ G__tag_memfunc_setup(G__get_linked_tagnum(&G__ManualTree2LN_TTree)); G__memfunc_setup("Process",735,G__ManualTree2_126_0_132, 110, -1, G__defined_typename("Long64_t"), 0, 4, 1, 1, 0, "Y - - 0 - selector C - 'Option_t' 10 '\"\"' option " "n - 'Long64_t' 0 '1000000000' nentries n - 'Long64_t' 0 '0' firstentry", (char*)NULL, (void*) NULL, 1); G__memfunc_setup("Branch",590,G__ManualTree2_126_0_187, 85, G__get_linked_tagnum(&G__ManualTree2LN_TBranch), -1, 0, 5, 1, 1, 0, "C - - 10 - name C - - 10 - classname " "Y - - 3 - addobj i - 'Int_t' 0 '32000' bufsize " "i - 'Int_t' 0 '99' splitlevel", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("Branch",590,G__ManualTree2_126_0_188, 85, G__get_linked_tagnum(&G__ManualTree2LN_TBranch), -1, 0, 4, 1, 1, 0, "C - - 10 - name Y - - 3 - addobj " "i - 'Int_t' 0 '32000' bufsize i - 'Int_t' 0 '99' splitlevel", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("SetBranchAddress",1600,G__ManualTree2_126_0_190, 121, -1, -1, 0, 3, 1, 1, 0, "C - - 10 - bname Y - - 2 - add " "U 'TBranch' - 2 '0' ptr", (char*)NULL, (void*) NULL, 0); G__tag_memfunc_reset(); } /********************************************************* * Member function information setup *********************************************************/ extern "C" void G__cpp_setup_memfuncManualTree2() { } /********************************************************* * Global variable information setup for each class *********************************************************/ static void G__cpp_setup_global0() { /* Setting up global variables */ G__resetplocal(); } static void G__cpp_setup_global1() { } static void G__cpp_setup_global2() { G__resetglobalenv(); } extern "C" void G__cpp_setup_globalManualTree2() { G__cpp_setup_global0(); G__cpp_setup_global1(); G__cpp_setup_global2(); } /********************************************************* * Global function information setup for each class *********************************************************/ static void G__cpp_setup_func0() { G__lastifuncposition(); } static void G__cpp_setup_func1() { } static void G__cpp_setup_func2() { G__resetifuncposition(); } extern "C" void G__cpp_setup_funcManualTree2() { G__cpp_setup_func0(); G__cpp_setup_func1(); G__cpp_setup_func2(); } /********************************************************* * Class,struct,union,enum tag information setup *********************************************************/ /* Setup class/struct taginfo */ G__linked_taginfo G__ManualTree2LN_TTree = { "TTree" , 99 , -1 }; G__linked_taginfo G__ManualTree2LN_TBranch = { "TBranch" , 99 , -1 }; G__linked_taginfo G__ManualTree2LN_TSelector = { "TSelector" , 99 , -1 }; /* Reset class/struct taginfo */ extern "C" void G__cpp_reset_tagtableManualTree2() { G__ManualTree2LN_TTree.tagnum = -1 ; G__ManualTree2LN_TBranch.tagnum = -1 ; G__ManualTree2LN_TSelector.tagnum = -1 ; } extern "C" void G__cpp_setup_tagtableManualTree2() { /* Setting up class,struct,union tag entry */ G__tagtable_setup(G__get_linked_tagnum(&G__ManualTree2LN_TTree),sizeof(TTree),-1,65280,"Tree descriptor (the main ROOT I/O class)",NULL,G__setup_memfuncTTree); G__get_linked_tagnum_fwd(&G__ManualTree2LN_TBranch); G__get_linked_tagnum_fwd(&G__ManualTree2LN_TSelector); } extern "C" void G__cpp_setupManualTree2(void) { G__check_setup_version(30051515,"G__cpp_setupManualTree2()"); G__set_cpp_environmentManualTree2(); G__cpp_setup_tagtableManualTree2(); G__cpp_setup_inheritanceManualTree2(); G__cpp_setup_typetableManualTree2(); G__cpp_setup_memvarManualTree2(); G__cpp_setup_memfuncManualTree2(); G__cpp_setup_globalManualTree2(); G__cpp_setup_funcManualTree2(); if(0==G__getsizep2memfunc()) G__get_sizep2memfuncManualTree2(); return; } class G__cpp_setup_initManualTree2 { public: G__cpp_setup_initManualTree2() { G__add_setup_func("ManualTree2",(G__incsetup)(&G__cpp_setupManualTree2)); G__call_setup_funcs(); } ~G__cpp_setup_initManualTree2() { G__remove_setup_func("ManualTree2"); } }; G__cpp_setup_initManualTree2 G__cpp_setup_initializerManualTree2; <commit_msg>fix the pointer level of the void* parameter to Branch<commit_after>// // File generated by c:\Devel\root_working\code\root.vc8\utils\src\rootcint_tmp.exe at Wed May 16 23:07:42 2007 // Do NOT change. Changes will be lost next time file is generated // #include "RConfig.h" #if !defined(R__ACCESS_IN_SYMBOL) //Break the privacy of classes -- Disabled for the moment #define private public #define protected public #endif // Since CINT ignores the std namespace, we need to do so in this file. namespace std {} using namespace std; #include "ManualTree2.h" #include "TClass.h" #include "TBuffer.h" #include "TMemberInspector.h" #include "TError.h" #ifndef G__ROOT #define G__ROOT #endif #include "RtypesImp.h" #include "TIsAProxy.h" // START OF SHADOWS namespace ROOT { namespace Shadow { } // of namespace Shadow } // of namespace ROOT // END OF SHADOWS /******************************************************** * tree/src/ManualTree2.cxx * CAUTION: DON'T CHANGE THIS FILE. THIS FILE IS AUTOMATICALLY GENERATED * FROM HEADER FILES LISTED IN G__setup_cpp_environmentXXX(). * CHANGE THOSE HEADER FILES AND REGENERATE THIS FILE. ********************************************************/ #ifdef G__MEMTEST #undef malloc #undef free #endif extern "C" void G__cpp_reset_tagtableManualTree2(); extern "C" void G__set_cpp_environmentManualTree2() { G__add_compiledheader("TTree.h"); G__cpp_reset_tagtableManualTree2(); } #include <new> extern "C" int G__cpp_dllrevManualTree2() { return(30051515); } /********************************************************* * Member function Interface Method *********************************************************/ /* TTree */ #include "ManualTree2Body.h" /* Setting up global function */ /********************************************************* * Member function Stub *********************************************************/ /********************************************************* * Global function Stub *********************************************************/ /********************************************************* * Get size of pointer to member function *********************************************************/ class G__Sizep2memfuncManualTree2 { public: G__Sizep2memfuncManualTree2(): p(&G__Sizep2memfuncManualTree2::sizep2memfunc) {} size_t sizep2memfunc() { return(sizeof(p)); } private: size_t (G__Sizep2memfuncManualTree2::*p)(); }; size_t G__get_sizep2memfuncManualTree2() { G__Sizep2memfuncManualTree2 a; G__setsizep2memfunc((int)a.sizep2memfunc()); return((size_t)a.sizep2memfunc()); } /********************************************************* * virtual base class offset calculation interface *********************************************************/ /* Setting up class inheritance */ /********************************************************* * Inheritance information setup/ *********************************************************/ extern "C" void G__cpp_setup_inheritanceManualTree2() { /* Setting up class inheritance */ } /********************************************************* * typedef information setup/ *********************************************************/ extern "C" void G__cpp_setup_typetableManualTree2() { /* Setting up typedef entry */ G__search_typename2("Int_t",105,-1,0,-1); G__setnewtype(-1,"Signed integer 4 bytes (int)",0); G__search_typename2("Option_t",99,-1,256,-1); G__setnewtype(-1,"Option string (const char)",0); G__search_typename2("Long64_t",110,-1,0,-1); G__setnewtype(-1,"Portable signed long integer 8 bytes",0); } /********************************************************* * Data Member information setup/ *********************************************************/ /* Setting up class,struct,union tag member variable */ extern "C" void G__cpp_setup_memvarManualTree2() { } /*********************************************************** ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ ************************************************************ ***********************************************************/ /********************************************************* * Member function information setup for each class *********************************************************/ static void G__setup_memfuncTTree(void) { /* TTree */ G__tag_memfunc_setup(G__get_linked_tagnum(&G__ManualTree2LN_TTree)); G__memfunc_setup("Process",735,G__ManualTree2_126_0_132, 110, -1, G__defined_typename("Long64_t"), 0, 4, 1, 1, 0, "Y - - 0 - selector C - 'Option_t' 10 '\"\"' option " "n - 'Long64_t' 0 '1000000000' nentries n - 'Long64_t' 0 '0' firstentry", (char*)NULL, (void*) NULL, 1); G__memfunc_setup("Branch",590,G__ManualTree2_126_0_187, 85, G__get_linked_tagnum(&G__ManualTree2LN_TBranch), -1, 0, 5, 1, 1, 0, "C - - 10 - name C - - 10 - classname " "Y - - 0 - addobj i - 'Int_t' 0 '32000' bufsize " "i - 'Int_t' 0 '99' splitlevel", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("Branch",590,G__ManualTree2_126_0_188, 85, G__get_linked_tagnum(&G__ManualTree2LN_TBranch), -1, 0, 4, 1, 1, 0, "C - - 10 - name Y - - 0 - addobj " "i - 'Int_t' 0 '32000' bufsize i - 'Int_t' 0 '99' splitlevel", (char*)NULL, (void*) NULL, 0); G__memfunc_setup("SetBranchAddress",1600,G__ManualTree2_126_0_190, 121, -1, -1, 0, 3, 1, 1, 0, "C - - 10 - bname Y - - 2 - add " "U 'TBranch' - 2 '0' ptr", (char*)NULL, (void*) NULL, 0); G__tag_memfunc_reset(); } /********************************************************* * Member function information setup *********************************************************/ extern "C" void G__cpp_setup_memfuncManualTree2() { } /********************************************************* * Global variable information setup for each class *********************************************************/ static void G__cpp_setup_global0() { /* Setting up global variables */ G__resetplocal(); } static void G__cpp_setup_global1() { } static void G__cpp_setup_global2() { G__resetglobalenv(); } extern "C" void G__cpp_setup_globalManualTree2() { G__cpp_setup_global0(); G__cpp_setup_global1(); G__cpp_setup_global2(); } /********************************************************* * Global function information setup for each class *********************************************************/ static void G__cpp_setup_func0() { G__lastifuncposition(); } static void G__cpp_setup_func1() { } static void G__cpp_setup_func2() { G__resetifuncposition(); } extern "C" void G__cpp_setup_funcManualTree2() { G__cpp_setup_func0(); G__cpp_setup_func1(); G__cpp_setup_func2(); } /********************************************************* * Class,struct,union,enum tag information setup *********************************************************/ /* Setup class/struct taginfo */ G__linked_taginfo G__ManualTree2LN_TTree = { "TTree" , 99 , -1 }; G__linked_taginfo G__ManualTree2LN_TBranch = { "TBranch" , 99 , -1 }; G__linked_taginfo G__ManualTree2LN_TSelector = { "TSelector" , 99 , -1 }; /* Reset class/struct taginfo */ extern "C" void G__cpp_reset_tagtableManualTree2() { G__ManualTree2LN_TTree.tagnum = -1 ; G__ManualTree2LN_TBranch.tagnum = -1 ; G__ManualTree2LN_TSelector.tagnum = -1 ; } extern "C" void G__cpp_setup_tagtableManualTree2() { /* Setting up class,struct,union tag entry */ G__tagtable_setup(G__get_linked_tagnum(&G__ManualTree2LN_TTree),sizeof(TTree),-1,65280,"Tree descriptor (the main ROOT I/O class)",NULL,G__setup_memfuncTTree); G__get_linked_tagnum_fwd(&G__ManualTree2LN_TBranch); G__get_linked_tagnum_fwd(&G__ManualTree2LN_TSelector); } extern "C" void G__cpp_setupManualTree2(void) { G__check_setup_version(30051515,"G__cpp_setupManualTree2()"); G__set_cpp_environmentManualTree2(); G__cpp_setup_tagtableManualTree2(); G__cpp_setup_inheritanceManualTree2(); G__cpp_setup_typetableManualTree2(); G__cpp_setup_memvarManualTree2(); G__cpp_setup_memfuncManualTree2(); G__cpp_setup_globalManualTree2(); G__cpp_setup_funcManualTree2(); if(0==G__getsizep2memfunc()) G__get_sizep2memfuncManualTree2(); return; } class G__cpp_setup_initManualTree2 { public: G__cpp_setup_initManualTree2() { G__add_setup_func("ManualTree2",(G__incsetup)(&G__cpp_setupManualTree2)); G__call_setup_funcs(); } ~G__cpp_setup_initManualTree2() { G__remove_setup_func("ManualTree2"); } }; G__cpp_setup_initManualTree2 G__cpp_setup_initializerManualTree2; <|endoftext|>
<commit_before>/* * Copyright (c) 2003 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. */ /* @file * EventQueue interfaces */ #ifndef __EVENTQ_HH__ #define __EVENTQ_HH__ #include <assert.h> #include <algorithm> #include <map> #include <string> #include <vector> #include "sim/host.hh" // for Tick #include "base/fast_alloc.hh" #include "sim/serialize.hh" #include "base/trace.hh" class EventQueue; // forward declaration /* * An item on an event queue. The action caused by a given * event is specified by deriving a subclass and overriding the * process() member function. */ class Event : public Serializable, public FastAlloc { friend class EventQueue; private: /// queue to which this event belongs (though it may or may not be /// scheduled on this queue yet) EventQueue *queue; Event *next; Tick _when; //!< timestamp when event should be processed int _priority; //!< event priority char _flags; protected: enum Flags { None = 0x0, Squashed = 0x1, Scheduled = 0x2, AutoDelete = 0x4, AutoSerialize = 0x8 }; bool getFlags(Flags f) const { return (_flags & f) == f; } void setFlags(Flags f) { _flags |= f; } void clearFlags(Flags f) { _flags &= ~f; } protected: EventQueue *theQueue() const { return queue; } #if TRACING_ON Tick when_created; //!< Keep track of creation time For debugging Tick when_scheduled; //!< Keep track of creation time For debugging virtual void trace(const char *action); //!< trace event activity #else void trace(const char *) {} #endif unsigned annotated_value; public: /// Event priorities, to provide tie-breakers for events scheduled /// at the same cycle. Most events are scheduled at the default /// priority; these values are used to control events that need to /// be ordered within a cycle. enum Priority { /// Breakpoints should happen before anything else, so we /// don't miss any action when debugging. Debug_Break_Pri = -100, /// For some reason "delayed" inter-cluster writebacks are /// scheduled before regular writebacks (which have default /// priority). Steve? Delayed_Writeback_Pri = -1, /// Default is zero for historical reasons. Default_Pri = 0, /// CPU switches schedule the new CPU's tick event for the /// same cycle (after unscheduling the old CPU's tick event). /// The switch needs to come before any tick events to make /// sure we don't tick both CPUs in the same cycle. CPU_Switch_Pri = 31, /// Serailization needs to occur before tick events also, so /// that a serialize/unserialize is identical to an on-line /// CPU switch. Serialize_Pri = 32, /// CPU ticks must come after other associated CPU events /// (such as writebacks). CPU_Tick_Pri = 50, /// Statistics events (dump, reset, etc.) come after /// everything else, but before exit. Stat_Event_Pri = 90, /// If we want to exit on this cycle, it's the very last thing /// we do. Sim_Exit_Pri = 100 }; /* * Event constructor * @param queue that the event gets scheduled on */ Event(EventQueue *q, Priority p = Default_Pri) : queue(q), next(NULL), _priority(p), _flags(None), #if TRACING_ON when_created(curTick), when_scheduled(0), #endif annotated_value(0) { } ~Event() {} virtual const std::string name() const { return csprintf("Event_%x", (uintptr_t)this); } /// Determine if the current event is scheduled bool scheduled() const { return getFlags(Scheduled); } /// Schedule the event with the current priority or default priority void schedule(Tick t); /// Reschedule the event with the current priority void reschedule(Tick t); /// Remove the event from the current schedule void deschedule(); /// Return a C string describing the event. This string should /// *not* be dynamically allocated; just a const char array /// describing the event class. virtual const char *description(); /// Dump the current event data void dump(); /* * This member function is invoked when the event is processed * (occurs). There is no default implementation; each subclass * must provide its own implementation. The event is not * automatically deleted after it is processed (to allow for * statically allocated event objects). * * If the AutoDestroy flag is set, the object is deleted once it * is processed. */ virtual void process() = 0; void annotate(unsigned value) { annotated_value = value; }; unsigned annotation() { return annotated_value; } /// Squash the current event void squash() { setFlags(Squashed); } /// Check whether the event is squashed bool squashed() { return getFlags(Squashed); } /// Get the time that the event is scheduled Tick when() const { return _when; } /// Get the event priority int priority() const { return _priority; } struct priority_compare : public std::binary_function<Event *, Event *, bool> { bool operator()(const Event *l, const Event *r) const { return l->when() >= r->when() || l->priority() >= r->priority(); } }; virtual void serialize(std::ostream &os); virtual void unserialize(Checkpoint *cp, const std::string &section); }; template <class T, void (T::* F)()> void DelayFunction(Tick when, T *object) { class DelayEvent : public Event { private: T *object; public: DelayEvent(Tick when, T *o) : Event(&mainEventQueue), object(o) { setFlags(AutoDestroy); schedule(when); } void process() { (object->*F)(); } const char *description() { return "delay"; } }; new DelayEvent(when, object); } /* * Queue of events sorted in time order */ class EventQueue : public Serializable { protected: std::string objName; private: Event *head; void insert(Event *event); void remove(Event *event); public: // constructor EventQueue(const std::string &n) : objName(n), head(NULL) {} virtual const std::string name() const { return objName; } // schedule the given event on this queue void schedule(Event *ev); void deschedule(Event *ev); void reschedule(Event *ev); Tick nextTick() { return head->when(); } void serviceOne(); // process all events up to the given timestamp. we inline a // quick test to see if there are any events to process; if so, // call the internal out-of-line version to process them all. void serviceEvents(Tick when) { while (!empty()) { if (nextTick() > when) break; assert(head->when() >= when && "event scheduled in the past"); serviceOne(); } } // default: process all events up to 'now' (curTick) void serviceEvents() { serviceEvents(curTick); } // return true if no events are queued bool empty() { return head == NULL; } void dump(); Tick nextEventTime() { return empty() ? curTick : head->when(); } virtual void serialize(std::ostream &os); virtual void unserialize(Checkpoint *cp, const std::string &section); }; ////////////////////// // // inline functions // // can't put these inside declaration due to circular dependence // between Event and EventQueue classes. // ////////////////////// // schedule at specified time (place on event queue specified via // constructor) inline void Event::schedule(Tick t) { assert(!scheduled()); setFlags(Scheduled); #if TRACING_ON when_scheduled = curTick; #endif _when = t; queue->schedule(this); } inline void Event::deschedule() { assert(scheduled()); clearFlags(Squashed); clearFlags(Scheduled); queue->deschedule(this); } inline void Event::reschedule(Tick t) { assert(scheduled()); clearFlags(Squashed); #if TRACING_ON when_scheduled = curTick; #endif _when = t; queue->reschedule(this); } inline void EventQueue::schedule(Event *event) { insert(event); if (DTRACE(Event)) event->trace("scheduled"); } inline void EventQueue::deschedule(Event *event) { remove(event); if (DTRACE(Event)) event->trace("descheduled"); } inline void EventQueue::reschedule(Event *event) { remove(event); insert(event); if (DTRACE(Event)) event->trace("rescheduled"); } ////////////////////// // // Main Event Queue // // Events on this queue are processed at the *beginning* of each // cycle, before the pipeline simulation is performed. // // defined in eventq.cc // ////////////////////// extern EventQueue mainEventQueue; #endif // __EVENTQ_HH__ <commit_msg>Add a simple event wrapper class that takes a class pointer and member function and will schedule it for the future.<commit_after>/* * Copyright (c) 2003 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. */ /* @file * EventQueue interfaces */ #ifndef __EVENTQ_HH__ #define __EVENTQ_HH__ #include <assert.h> #include <algorithm> #include <map> #include <string> #include <vector> #include "sim/host.hh" // for Tick #include "base/fast_alloc.hh" #include "sim/serialize.hh" #include "base/trace.hh" class EventQueue; // forward declaration /* * An item on an event queue. The action caused by a given * event is specified by deriving a subclass and overriding the * process() member function. */ class Event : public Serializable, public FastAlloc { friend class EventQueue; private: /// queue to which this event belongs (though it may or may not be /// scheduled on this queue yet) EventQueue *queue; Event *next; Tick _when; //!< timestamp when event should be processed int _priority; //!< event priority char _flags; protected: enum Flags { None = 0x0, Squashed = 0x1, Scheduled = 0x2, AutoDelete = 0x4, AutoSerialize = 0x8 }; bool getFlags(Flags f) const { return (_flags & f) == f; } void setFlags(Flags f) { _flags |= f; } void clearFlags(Flags f) { _flags &= ~f; } protected: EventQueue *theQueue() const { return queue; } #if TRACING_ON Tick when_created; //!< Keep track of creation time For debugging Tick when_scheduled; //!< Keep track of creation time For debugging virtual void trace(const char *action); //!< trace event activity #else void trace(const char *) {} #endif unsigned annotated_value; public: /// Event priorities, to provide tie-breakers for events scheduled /// at the same cycle. Most events are scheduled at the default /// priority; these values are used to control events that need to /// be ordered within a cycle. enum Priority { /// Breakpoints should happen before anything else, so we /// don't miss any action when debugging. Debug_Break_Pri = -100, /// For some reason "delayed" inter-cluster writebacks are /// scheduled before regular writebacks (which have default /// priority). Steve? Delayed_Writeback_Pri = -1, /// Default is zero for historical reasons. Default_Pri = 0, /// CPU switches schedule the new CPU's tick event for the /// same cycle (after unscheduling the old CPU's tick event). /// The switch needs to come before any tick events to make /// sure we don't tick both CPUs in the same cycle. CPU_Switch_Pri = 31, /// Serailization needs to occur before tick events also, so /// that a serialize/unserialize is identical to an on-line /// CPU switch. Serialize_Pri = 32, /// CPU ticks must come after other associated CPU events /// (such as writebacks). CPU_Tick_Pri = 50, /// Statistics events (dump, reset, etc.) come after /// everything else, but before exit. Stat_Event_Pri = 90, /// If we want to exit on this cycle, it's the very last thing /// we do. Sim_Exit_Pri = 100 }; /* * Event constructor * @param queue that the event gets scheduled on */ Event(EventQueue *q, Priority p = Default_Pri) : queue(q), next(NULL), _priority(p), _flags(None), #if TRACING_ON when_created(curTick), when_scheduled(0), #endif annotated_value(0) { } ~Event() {} virtual const std::string name() const { return csprintf("Event_%x", (uintptr_t)this); } /// Determine if the current event is scheduled bool scheduled() const { return getFlags(Scheduled); } /// Schedule the event with the current priority or default priority void schedule(Tick t); /// Reschedule the event with the current priority void reschedule(Tick t); /// Remove the event from the current schedule void deschedule(); /// Return a C string describing the event. This string should /// *not* be dynamically allocated; just a const char array /// describing the event class. virtual const char *description(); /// Dump the current event data void dump(); /* * This member function is invoked when the event is processed * (occurs). There is no default implementation; each subclass * must provide its own implementation. The event is not * automatically deleted after it is processed (to allow for * statically allocated event objects). * * If the AutoDestroy flag is set, the object is deleted once it * is processed. */ virtual void process() = 0; void annotate(unsigned value) { annotated_value = value; }; unsigned annotation() { return annotated_value; } /// Squash the current event void squash() { setFlags(Squashed); } /// Check whether the event is squashed bool squashed() { return getFlags(Squashed); } /// Get the time that the event is scheduled Tick when() const { return _when; } /// Get the event priority int priority() const { return _priority; } struct priority_compare : public std::binary_function<Event *, Event *, bool> { bool operator()(const Event *l, const Event *r) const { return l->when() >= r->when() || l->priority() >= r->priority(); } }; virtual void serialize(std::ostream &os); virtual void unserialize(Checkpoint *cp, const std::string &section); }; template <class T, void (T::* F)()> void DelayFunction(Tick when, T *object) { class DelayEvent : public Event { private: T *object; public: DelayEvent(Tick when, T *o) : Event(&mainEventQueue), object(o) { setFlags(AutoDestroy); schedule(when); } void process() { (object->*F)(); } const char *description() { return "delay"; } }; new DelayEvent(when, object); } template <class T, void (T::* F)()> class EventWrapper : public Event { private: T *object; public: EventWrapper(T *obj, EventQueue *q = &mainEventQueue, Priority p = Default_Pri) : Event(q, p), object(obj) {} void process() { (object->*F)(); } }; /* * Queue of events sorted in time order */ class EventQueue : public Serializable { protected: std::string objName; private: Event *head; void insert(Event *event); void remove(Event *event); public: // constructor EventQueue(const std::string &n) : objName(n), head(NULL) {} virtual const std::string name() const { return objName; } // schedule the given event on this queue void schedule(Event *ev); void deschedule(Event *ev); void reschedule(Event *ev); Tick nextTick() { return head->when(); } void serviceOne(); // process all events up to the given timestamp. we inline a // quick test to see if there are any events to process; if so, // call the internal out-of-line version to process them all. void serviceEvents(Tick when) { while (!empty()) { if (nextTick() > when) break; assert(head->when() >= when && "event scheduled in the past"); serviceOne(); } } // default: process all events up to 'now' (curTick) void serviceEvents() { serviceEvents(curTick); } // return true if no events are queued bool empty() { return head == NULL; } void dump(); Tick nextEventTime() { return empty() ? curTick : head->when(); } virtual void serialize(std::ostream &os); virtual void unserialize(Checkpoint *cp, const std::string &section); }; ////////////////////// // // inline functions // // can't put these inside declaration due to circular dependence // between Event and EventQueue classes. // ////////////////////// // schedule at specified time (place on event queue specified via // constructor) inline void Event::schedule(Tick t) { assert(!scheduled()); setFlags(Scheduled); #if TRACING_ON when_scheduled = curTick; #endif _when = t; queue->schedule(this); } inline void Event::deschedule() { assert(scheduled()); clearFlags(Squashed); clearFlags(Scheduled); queue->deschedule(this); } inline void Event::reschedule(Tick t) { assert(scheduled()); clearFlags(Squashed); #if TRACING_ON when_scheduled = curTick; #endif _when = t; queue->reschedule(this); } inline void EventQueue::schedule(Event *event) { insert(event); if (DTRACE(Event)) event->trace("scheduled"); } inline void EventQueue::deschedule(Event *event) { remove(event); if (DTRACE(Event)) event->trace("descheduled"); } inline void EventQueue::reschedule(Event *event) { remove(event); insert(event); if (DTRACE(Event)) event->trace("rescheduled"); } ////////////////////// // // Main Event Queue // // Events on this queue are processed at the *beginning* of each // cycle, before the pipeline simulation is performed. // // defined in eventq.cc // ////////////////////// extern EventQueue mainEventQueue; #endif // __EVENTQ_HH__ <|endoftext|>
<commit_before>/* Copyright 2013 Roman Kurbatov * * 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. * * This file was modified by Yurii Litvinov to make it comply with the requirements of trikRuntime * project. See git revision history for detailed changes. */ #include "fileManagerWidget.h" #include <QtCore/QDir> #include <QtCore/QTimer> #include <QtGui/QKeyEvent> using namespace trikGui; FileManagerWidget::FileManagerWidget(Controller &controller, MainWidget::FileManagerRootType fileManagerRoot , QWidget *parent) : TrikGuiDialog(parent) , mController(controller) { if (fileManagerRoot == MainWidget::FileManagerRootType::allFS) { mRootDirPath = QDir::rootPath(); } else { // if (fileManagerRoot == MainWidget::FileManagerRootType::scriptsDir) mRootDirPath = mController.scriptsDirPath(); } QDir::setCurrent(mController.startDirPath()); QDir dir; dir.mkdir(mController.scriptsDirName()); QDir::setCurrent(mController.scriptsDirPath()); mFileSystemModel.setRootPath(mRootDirPath); mFileSystemModel.setFilter(QDir::AllEntries | QDir::Hidden | QDir::System | QDir::NoDot); connect(&mFileSystemModel , SIGNAL(directoryLoaded(QString)) , this , SLOT(onDirectoryLoaded(QString)) ); mFileSystemView.setModel(&mFileSystemModel); mLayout.addWidget(&mCurrentPathLabel); mLayout.addWidget(&mFileSystemView); setLayout(&mLayout); mFileSystemView.setSelectionMode(QAbstractItemView::SingleSelection); mFileSystemView.setFocus(); showCurrentDir(); } FileManagerWidget::~FileManagerWidget() { } QString FileManagerWidget::menuEntry() { return tr("File Manager"); } void FileManagerWidget::renewFocus() { mFileSystemView.setFocus(); } void FileManagerWidget::open() { QModelIndex const &index = mFileSystemView.currentIndex(); if (mFileSystemModel.isDir(index)) { if (QDir::setCurrent(mFileSystemModel.filePath(index))) { showCurrentDir(); } } else { mOpenDeleteBox.showMessage(); FileManagerMessageBox::FileState const choice = mOpenDeleteBox.userAnswer(); switch (choice) { case FileManagerMessageBox::FileState::Open: mController.runFile(mFileSystemModel.filePath(index)); break; case FileManagerMessageBox::FileState::Delete: mFileSystemModel.remove(index); break; default: break; } } } void FileManagerWidget::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Return: { open(); break; } default: { TrikGuiDialog::keyPressEvent(event); break; } } } QString FileManagerWidget::showCurrentPath() { QString result = QDir::currentPath(); result.remove(mRootDirPath); if (result.isEmpty()) { result = "/"; } return result; } void FileManagerWidget::showCurrentDir() { mCurrentPathLabel.setText(showCurrentPath()); QDir::Filters filters = mFileSystemModel.filter(); if (QDir::currentPath() == mRootDirPath) { filters |= QDir::NoDotDot; } else { filters &= ~QDir::NoDotDot; } filters &= ~QDir::Hidden; mFileSystemModel.setFilter(filters); mFileSystemView.setRootIndex(mFileSystemModel.index(QDir::currentPath())); /// @todo Here and several lines down we use QTimer /// to fix a bug with selecting first item. Rewrite it. QTimer::singleShot(200, this, SLOT(renewCurrentIndex())); } void FileManagerWidget::onDirectoryLoaded(QString const &path) { if (QDir::currentPath() != path) { return; } QTimer::singleShot(200, this, SLOT(renewCurrentIndex())); } void FileManagerWidget::renewCurrentIndex() { mFileSystemView.setFocus(); QModelIndex const currentIndex = mFileSystemModel.index( 0 , 0 , mFileSystemModel.index(QDir::currentPath()) ); mFileSystemView.selectionModel()->select(currentIndex, QItemSelectionModel::ClearAndSelect); mFileSystemView.setCurrentIndex(currentIndex); } <commit_msg>fixed mCurrentPathLabel-path (now with '/')<commit_after>/* Copyright 2013 Roman Kurbatov * * 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. * * This file was modified by Yurii Litvinov to make it comply with the requirements of trikRuntime * project. See git revision history for detailed changes. */ #include "fileManagerWidget.h" #include <QtCore/QDir> #include <QtCore/QTimer> #include <QtGui/QKeyEvent> using namespace trikGui; FileManagerWidget::FileManagerWidget(Controller &controller, MainWidget::FileManagerRootType fileManagerRoot , QWidget *parent) : TrikGuiDialog(parent) , mController(controller) { if (fileManagerRoot == MainWidget::FileManagerRootType::allFS) { mRootDirPath = QDir::rootPath(); } else { // if (fileManagerRoot == MainWidget::FileManagerRootType::scriptsDir) mRootDirPath = mController.scriptsDirPath(); } QDir::setCurrent(mController.startDirPath()); QDir dir; dir.mkdir(mController.scriptsDirName()); QDir::setCurrent(mController.scriptsDirPath()); mFileSystemModel.setRootPath(mRootDirPath); mFileSystemModel.setFilter(QDir::AllEntries | QDir::Hidden | QDir::System | QDir::NoDot); connect(&mFileSystemModel , SIGNAL(directoryLoaded(QString)) , this , SLOT(onDirectoryLoaded(QString)) ); mFileSystemView.setModel(&mFileSystemModel); mLayout.addWidget(&mCurrentPathLabel); mLayout.addWidget(&mFileSystemView); setLayout(&mLayout); mFileSystemView.setSelectionMode(QAbstractItemView::SingleSelection); mFileSystemView.setFocus(); showCurrentDir(); } FileManagerWidget::~FileManagerWidget() { } QString FileManagerWidget::menuEntry() { return tr("File Manager"); } void FileManagerWidget::renewFocus() { mFileSystemView.setFocus(); } void FileManagerWidget::open() { QModelIndex const &index = mFileSystemView.currentIndex(); if (mFileSystemModel.isDir(index)) { if (QDir::setCurrent(mFileSystemModel.filePath(index))) { showCurrentDir(); } } else { mOpenDeleteBox.showMessage(); FileManagerMessageBox::FileState const choice = mOpenDeleteBox.userAnswer(); switch (choice) { case FileManagerMessageBox::FileState::Open: mController.runFile(mFileSystemModel.filePath(index)); break; case FileManagerMessageBox::FileState::Delete: mFileSystemModel.remove(index); break; default: break; } } } void FileManagerWidget::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Return: { open(); break; } default: { TrikGuiDialog::keyPressEvent(event); break; } } } QString FileManagerWidget::showCurrentPath() { QString result = QDir::currentPath(); if (mRootDirPath != "/") { result.remove(mRootDirPath); } if (result.isEmpty()) { result = "/"; } return result; } void FileManagerWidget::showCurrentDir() { mCurrentPathLabel.setText(showCurrentPath()); QDir::Filters filters = mFileSystemModel.filter(); if (QDir::currentPath() == mRootDirPath) { filters |= QDir::NoDotDot; } else { filters &= ~QDir::NoDotDot; } filters &= ~QDir::Hidden; mFileSystemModel.setFilter(filters); mFileSystemView.setRootIndex(mFileSystemModel.index(QDir::currentPath())); /// @todo Here and several lines down we use QTimer /// to fix a bug with selecting first item. Rewrite it. QTimer::singleShot(200, this, SLOT(renewCurrentIndex())); } void FileManagerWidget::onDirectoryLoaded(QString const &path) { if (QDir::currentPath() != path) { return; } QTimer::singleShot(200, this, SLOT(renewCurrentIndex())); } void FileManagerWidget::renewCurrentIndex() { mFileSystemView.setFocus(); QModelIndex const currentIndex = mFileSystemModel.index( 0 , 0 , mFileSystemModel.index(QDir::currentPath()) ); mFileSystemView.selectionModel()->select(currentIndex, QItemSelectionModel::ClearAndSelect); mFileSystemView.setCurrentIndex(currentIndex); } <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbWrapperParameterList.h" #include "otbWrapperQtWidgetListEditItemModel.h" #include "otbWrapperQtWidgetListEditWidget.h" #include "otbWrapperQtWidgetParameterList.h" namespace otb { namespace Wrapper { /*****************************************************************************/ QtWidgetParameterList ::QtWidgetParameterList( AbstractParameterList * param, QtWidgetModel * m ) : QtWidgetParameterBase( param, m ) { assert( m!=nullptr ); QObject::connect( this, SIGNAL( NotifyUpdate() ), m, SLOT( NotifyUpdate() ) ); } /*****************************************************************************/ QtWidgetParameterList ::~QtWidgetParameterList() { } /*****************************************************************************/ void QtWidgetParameterList ::DoUpdateGUI() { } /*****************************************************************************/ void QtWidgetParameterList ::DoCreateWidget() { // // List-edit widget. ListEditWidget * widget = new ListEditWidget(); assert( widget->GetItemModel()!=nullptr ); assert( dynamic_cast< StringListInterface * >( GetParam() )!=nullptr ); widget->GetItemModel()->SetStringList( dynamic_cast< StringListInterface * >( GetParam() ) ); // // Global Layout QGridLayout * layout = new QGridLayout(); layout->setSpacing( 1 ); layout->setContentsMargins( 2, 2, 2, 2 ); layout->addWidget( widget ); setLayout( layout ); // // Connections. { QAbstractItemModel * model = widget->GetItemModel(); assert( model!=nullptr ); QObject::connect( model, SIGNAL( dataChanged( const QModelIndex &, const QModelIndex & ) ), this, SLOT( OnDataChanged( const QModelIndex &, const QModelIndex & ) ) ); QObject::connect( model, SIGNAL( modelReset() ), this, SLOT( OnModelReset() ) ); QObject::connect( model, SIGNAL( rowsInserted( const QModelIndex &, int, int ) ), this, SLOT( OnRowsInserted( const QModelIndex &, int, int ) ) ); QObject::connect( model, SIGNAL( rowsRemoved( const QModelIndex &, int, int ) ), this, SLOT( OnRowsRemoved( const QModelIndex &, int, int ) ) ); } } /*****************************************************************************/ void QtWidgetParameterList ::OnDataChanged( const QModelIndex &, const QModelIndex & ) { qDebug() << this << "::OnDataChanged()"; assert( GetModel()!=nullptr ); emit NotifyUpdate(); } /*****************************************************************************/ void QtWidgetParameterList ::OnModelReset() { qDebug() << this << "::OnModelReset()"; emit NotifyUpdate(); } /*****************************************************************************/ void QtWidgetParameterList ::OnRowsInserted( const QModelIndex &, int, int ) { qDebug() << this << "::OnRowsInserted()"; emit NotifyUpdate(); } /*****************************************************************************/ void QtWidgetParameterList ::OnRowsRemoved( const QModelIndex &, int, int ) { qDebug() << this << "::OnRowsRemoved()"; emit NotifyUpdate(); } } } <commit_msg>ENH: Disabled debug traces.<commit_after>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbWrapperParameterList.h" #include "otbWrapperQtWidgetListEditItemModel.h" #include "otbWrapperQtWidgetListEditWidget.h" #include "otbWrapperQtWidgetParameterList.h" namespace otb { namespace Wrapper { /*****************************************************************************/ QtWidgetParameterList ::QtWidgetParameterList( AbstractParameterList * param, QtWidgetModel * m ) : QtWidgetParameterBase( param, m ) { assert( m!=nullptr ); QObject::connect( this, SIGNAL( NotifyUpdate() ), m, SLOT( NotifyUpdate() ) ); } /*****************************************************************************/ QtWidgetParameterList ::~QtWidgetParameterList() { } /*****************************************************************************/ void QtWidgetParameterList ::DoUpdateGUI() { } /*****************************************************************************/ void QtWidgetParameterList ::DoCreateWidget() { // // List-edit widget. ListEditWidget * widget = new ListEditWidget(); assert( widget->GetItemModel()!=nullptr ); assert( dynamic_cast< StringListInterface * >( GetParam() )!=nullptr ); widget->GetItemModel()->SetStringList( dynamic_cast< StringListInterface * >( GetParam() ) ); // // Global Layout QGridLayout * layout = new QGridLayout(); layout->setSpacing( 1 ); layout->setContentsMargins( 2, 2, 2, 2 ); layout->addWidget( widget ); setLayout( layout ); // // Connections. { QAbstractItemModel * model = widget->GetItemModel(); assert( model!=nullptr ); QObject::connect( model, SIGNAL( dataChanged( const QModelIndex &, const QModelIndex & ) ), this, SLOT( OnDataChanged( const QModelIndex &, const QModelIndex & ) ) ); QObject::connect( model, SIGNAL( modelReset() ), this, SLOT( OnModelReset() ) ); QObject::connect( model, SIGNAL( rowsInserted( const QModelIndex &, int, int ) ), this, SLOT( OnRowsInserted( const QModelIndex &, int, int ) ) ); QObject::connect( model, SIGNAL( rowsRemoved( const QModelIndex &, int, int ) ), this, SLOT( OnRowsRemoved( const QModelIndex &, int, int ) ) ); } } /*****************************************************************************/ void QtWidgetParameterList ::OnDataChanged( const QModelIndex &, const QModelIndex & ) { // qDebug() << this << "::OnDataChanged()"; assert( GetModel()!=nullptr ); emit NotifyUpdate(); } /*****************************************************************************/ void QtWidgetParameterList ::OnModelReset() { // qDebug() << this << "::OnModelReset()"; emit NotifyUpdate(); } /*****************************************************************************/ void QtWidgetParameterList ::OnRowsInserted( const QModelIndex &, int, int ) { // qDebug() << this << "::OnRowsInserted()"; emit NotifyUpdate(); } /*****************************************************************************/ void QtWidgetParameterList ::OnRowsRemoved( const QModelIndex &, int, int ) { // qDebug() << this << "::OnRowsRemoved()"; emit NotifyUpdate(); } } } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "itkImageToImageFilter.h" #include "otbMaximumAutocorrelationFactorImageFilter.h" #include "otbPCAImageFilter.h" #include "otbNAPCAImageFilter.h" #include "otbLocalActivityVectorImageFilter.h" #include "otbMaximumAutocorrelationFactorImageFilter.h" #include "otbFastICAImageFilter.h" #include "otbFastICAInternalOptimizerVectorImageFilter.h" //#include "otbVirtualDimensionality.h" #include "otbStreamingMinMaxVectorImageFilter.h" #include "otbVectorRescaleIntensityImageFilter.h" namespace otb { namespace Wrapper { class DimensionalityReduction: public Application { public: /** Standard class typedefs. */ typedef DimensionalityReduction Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; // Dimensionality reduction typedef typedef otb::MaximumAutocorrelationFactorImageFilter<FloatVectorImageType, FloatVectorImageType> MAFFilterType; typedef itk::ImageToImageFilter<FloatVectorImageType, FloatVectorImageType> DimensionalityReductionFilter; // Reduction dimensio filters typedef otb::PCAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD> PCAForwardFilterType; typedef otb::PCAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::INVERSE> PCAInverseFilterType; //typedef otb::PCAImageFilter< FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD > typedef otb::LocalActivityVectorImageFilter<FloatVectorImageType, FloatVectorImageType> NoiseFilterType; typedef otb::NAPCAImageFilter<FloatVectorImageType, FloatVectorImageType, NoiseFilterType, otb::Transform::FORWARD> NAPCAForwardFilterType; typedef otb::NAPCAImageFilter<FloatVectorImageType, FloatVectorImageType, NoiseFilterType, otb::Transform::INVERSE> NAPCAInverseFilterType; typedef otb::MaximumAutocorrelationFactorImageFilter<FloatVectorImageType, FloatVectorImageType> MAFForwardFilterType; typedef otb::FastICAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD> ICAForwardFilterType; typedef otb::FastICAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::INVERSE> ICAInverseFilterType; typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType> StreamingStatisticsVectorImageFilterType; typedef StreamingStatisticsVectorImageFilterType::MatrixObjectType::ComponentType MatrixType; //typedef otb::VirtualDimensionality<double> VDFilterType; // output rescale typedef otb::StreamingMinMaxVectorImageFilter<FloatVectorImageType> MinMaxFilterType; typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType> RescaleImageFilterType; /** Standard macro */ itkNewMacro(Self) ; itkTypeMacro(DimensionalityReduction, otb::Wrapper::Application) ; private: void DoInit() { SetName("DimensionalityReduction"); SetDescription("Perform Dimension reduction of the input image."); SetDocName("Dimensionality reduction"); SetDocLongDescription("Performs dimensionality reduction on input image. PCA,NA-PCA,MAF,ICA methods are available."); SetDocLimitations( "Though the inverse transform can be computed, this application only provides the forward transform for now."); SetDocAuthors("OTB-Team"); SetDocSeeAlso( "\"Kernel maximum autocorrelation factor and minimum noise fraction transformations,\" IEEE Transactions on Image Processing, vol. 20, no. 3, pp. 612-624, (2011)"); AddDocTag(Tags::DimensionReduction); AddDocTag(Tags::Filter); AddParameter(ParameterType_InputImage, "in", "Input Image"); SetParameterDescription("in", "The input image to apply dimensionality reduction."); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out", "output image. Components are ordered by decreasing eigenvalues."); AddParameter(ParameterType_Group, "rescale", "Rescale Output."); MandatoryOff("rescale"); // AddChoice("rescale.no","No rescale"); // AddChoice("rescale.minmax","rescale to min max value"); AddParameter(ParameterType_Float, "rescale.outmin", "Output min value"); AddParameter(ParameterType_Float, "rescale.outmax", "Output max value"); SetDefaultParameterFloat("rescale.outmin", 0.0); SetParameterDescription("rescale.outmin", "Minimum value of the output image."); SetDefaultParameterFloat("rescale.outmax", 255.0); SetParameterDescription("rescale.outmax", "Maximum value of the output image."); AddParameter(ParameterType_OutputImage, "outinv", " Inverse Output Image"); SetParameterDescription("outinv", "reconstruct output image."); MandatoryOff("outinv"); AddParameter(ParameterType_Choice, "method", "Algorithm"); SetParameterDescription("method", "Selection of the reduction dimension method."); AddChoice("method.pca", "PCA"); SetParameterDescription("method.pca", "Principal Component Analysis."); AddChoice("method.napca", "NA-PCA"); SetParameterDescription("method.napca", "Noise Adjusted Principal Component Analysis."); AddParameter(ParameterType_Int, "method.napca.radiusx", "Set the x radius of the sliding window."); SetMinimumParameterIntValue("method.napca.radiusx", 1); SetDefaultParameterInt("method.napca.radiusx", 1); AddParameter(ParameterType_Int, "method.napca.radiusy", "Set the y radius of the sliding window."); SetMinimumParameterIntValue("method.napca.radiusy", 1); SetDefaultParameterInt("method.napca.radiusy", 1); AddChoice("method.maf", "MAF"); SetParameterDescription("method.maf", "Maximum Autocorrelation Factor."); AddChoice("method.ica", "ICA"); SetParameterDescription("method.ica", "Independant Component Analysis."); AddParameter(ParameterType_Int, "method.ica.iter", "number of iterations "); SetMinimumParameterIntValue("method.ica.iter", 1); SetDefaultParameterInt("method.ica.iter", 20); MandatoryOff("method.ica.iter"); AddParameter(ParameterType_Float, "method.ica.mu", "Give the increment weight of W in [0, 1]"); SetMinimumParameterFloatValue("method.ica.mu", 0.); SetMaximumParameterFloatValue("method.ica.mu", 1.); SetDefaultParameterFloat("method.ica.mu", 1.); MandatoryOff("method.ica.mu"); //AddChoice("method.vd","virual Dimension"); //SetParameterDescription("method.vd","Virtual Dimension."); //MandatoryOff("method"); AddParameter(ParameterType_Int, "nbcomp", "Number of Components."); SetParameterDescription("nbcomp", "Number of relevant components kept. By default all components are kept."); SetDefaultParameterInt("nbcomp", 0); MandatoryOff("nbcomp"); SetMinimumParameterIntValue("nbcomp", 0); AddParameter(ParameterType_Empty, "normalize", "Normalize."); SetParameterDescription("normalize", "center AND reduce data before Dimensionality reduction."); MandatoryOff("normalize"); AddParameter(ParameterType_OutputFilename, "outmatrix", "Transformation matrix output"); SetParameterDescription("outmatrix", "Filename to store the transformation matrix (csv format)"); MandatoryOff("outmatrix"); // Doc example parameter settings SetDocExampleParameterValue("in", "cupriteSubHsi.tif"); SetDocExampleParameterValue("out", "FilterOutput.tif"); SetDocExampleParameterValue("method", "pca"); } void DoUpdateParameters() { } void DoExecute() { // Get Parameters int nbComp = GetParameterInt("nbcomp"); bool normalize = HasValue("normalize"); bool rescale = IsParameterEnabled("rescale"); bool invTransform = HasValue("outinv"); switch (GetParameterInt("method")) { // PCA Algorithm case 0: { otbAppLogDEBUG( << "PCA Algorithm "); PCAForwardFilterType::Pointer filter = PCAForwardFilterType::New(); m_ForwardFilter = filter; PCAInverseFilterType::Pointer invFilter = PCAInverseFilterType::New(); m_InverseFilter = invFilter; filter->SetInput(GetParameterFloatVectorImage("in")); filter->SetNumberOfPrincipalComponentsRequired(nbComp); filter->SetUseNormalization(normalize); m_ForwardFilter->Update(); if (invTransform) { invFilter->SetInput(m_ForwardFilter->GetOutput()); if (normalize) { otbAppLogINFO( << "Normalization MeanValue :"<<filter->GetMeanValues()<< "StdValue :" <<filter->GetStdDevValues() ); invFilter->SetMeanValues(filter->GetMeanValues()); invFilter->SetStdDevValues(filter->GetStdDevValues()); } invFilter->SetTransformationMatrix(filter->GetTransformationMatrix()); m_TransformationMatrix = invFilter->GetTransformationMatrix(); } m_TransformationMatrix = filter->GetTransformationMatrix(); break; } case 1: { otbAppLogDEBUG( << "NA-PCA Algorithm "); // NA-PCA unsigned int radiusX = static_cast<unsigned int> (GetParameterInt("method.napca.radiusx")); unsigned int radiusY = static_cast<unsigned int> (GetParameterInt("method.napca.radiusy")); // Noise filtering NoiseFilterType::RadiusType radius = { { radiusX, radiusY } }; NAPCAForwardFilterType::Pointer filter = NAPCAForwardFilterType::New(); m_ForwardFilter = filter; NAPCAInverseFilterType::Pointer invFilter = NAPCAInverseFilterType::New(); m_InverseFilter = invFilter; filter->SetInput(GetParameterFloatVectorImage("in")); filter->SetNumberOfPrincipalComponentsRequired(nbComp); filter->SetUseNormalization(normalize); filter->GetNoiseImageFilter()->SetRadius(radius); m_ForwardFilter->Update(); if (invTransform) { otbAppLogDEBUG( << "Compute Inverse Transform"); invFilter->SetInput(m_ForwardFilter->GetOutput()); invFilter->SetMeanValues(filter->GetMeanValues()); if (normalize) { invFilter->SetStdDevValues(filter->GetStdDevValues()); } invFilter->SetTransformationMatrix(filter->GetTransformationMatrix()); m_TransformationMatrix = invFilter->GetTransformationMatrix(); } m_TransformationMatrix = filter->GetTransformationMatrix(); break; } case 2: { otbAppLogDEBUG( << "MAF Algorithm "); MAFForwardFilterType::Pointer filter = MAFForwardFilterType::New(); m_ForwardFilter = filter; filter->SetInput(GetParameterFloatVectorImage("in")); m_ForwardFilter->Update(); otbAppLogINFO( << "V :"<<std::endl<<filter->GetV()<<"Auto-Correlation :"<<std::endl <<filter->GetAutoCorrelation() ); break; } case 3: { otbAppLogDEBUG( << "Fast ICA Algorithm "); unsigned int nbIterations = static_cast<unsigned int> (GetParameterInt("method.ica.iter")); double mu = static_cast<double> (GetParameterFloat("method.ica.mu")); ICAForwardFilterType::Pointer filter = ICAForwardFilterType::New(); m_ForwardFilter = filter; ICAInverseFilterType::Pointer invFilter = ICAInverseFilterType::New(); m_InverseFilter = invFilter; filter->SetInput(GetParameterFloatVectorImage("in")); filter->SetNumberOfPrincipalComponentsRequired(nbComp); filter->SetNumberOfIterations(nbIterations); filter->SetMu(mu); m_ForwardFilter->Update(); if (invTransform) { otbAppLogDEBUG( << "Compute Inverse Transform"); invFilter->SetInput(m_ForwardFilter->GetOutput()); if (normalize) { invFilter->SetMeanValues(filter->GetMeanValues()); invFilter->SetStdDevValues(filter->GetStdDevValues()); } invFilter->SetPCATransformationMatrix(filter->GetPCATransformationMatrix()); invFilter->SetTransformationMatrix(filter->GetTransformationMatrix()); } m_TransformationMatrix = filter->GetTransformationMatrix(); break; } /* case 4: { otbAppLogDEBUG( << "VD Algorithm"); break; }*/ default: { otbAppLogFATAL(<<"non defined method "<<GetParameterInt("method")<<std::endl); break; } return; } if (invTransform) { if (GetParameterInt("method") == 2) //MAF or VD { otbAppLogWARNING(<<"This application only provides the forward transform ."); } else SetParameterOutputImage("outinv", m_InverseFilter->GetOutput()); } //Write transformation matrix if (this->GetParameterString("outmatrix").c_str()) { if (GetParameterInt("method") == 2) //MAF or VD { otbAppLogWARNING(<<"No transformation matrix available for MAF."); } else { //Write transformation matrix std::ofstream outFile; outFile.open(this->GetParameterString("outmatrix").c_str()); outFile << std::fixed; outFile.precision(10); outFile << m_TransformationMatrix; // if (invTransform) // { // outFile << m_InverseFilter->GetTransformationMatrix(); // } // else // { // outFile << m_ForwardFilter->GetTransformationMatrix(); // } //outFile << std::endl; outFile.close(); } } if (!rescale) { SetParameterOutputImage("out", m_ForwardFilter->GetOutput()); } else { otbAppLogDEBUG( << "Rescaling " ) otbAppLogDEBUG( << "Starting Min/Max computation" ) m_MinMaxFilter = MinMaxFilterType::New(); m_MinMaxFilter->SetInput(m_ForwardFilter->GetOutput()); m_MinMaxFilter->GetStreamer()->SetNumberOfLinesStrippedStreaming(50); AddProcess(m_MinMaxFilter->GetStreamer(), "Min/Max computing"); m_MinMaxFilter->Update(); otbAppLogDEBUG( << "Min/Max computation done : min=" << m_MinMaxFilter->GetMinimum() << " max=" << m_MinMaxFilter->GetMaximum() ) FloatVectorImageType::PixelType inMin, inMax; m_RescaleFilter = RescaleImageFilterType::New(); m_RescaleFilter->SetInput(m_ForwardFilter->GetOutput()); m_RescaleFilter->SetInputMinimum(m_MinMaxFilter->GetMinimum()); m_RescaleFilter->SetInputMaximum(m_MinMaxFilter->GetMaximum()); FloatVectorImageType::PixelType outMin, outMax; outMin.SetSize(m_ForwardFilter->GetOutput()->GetNumberOfComponentsPerPixel()); outMax.SetSize(m_ForwardFilter->GetOutput()->GetNumberOfComponentsPerPixel()); outMin.Fill(GetParameterFloat("rescale.outmin")); outMax.Fill(GetParameterFloat("rescale.outmax")); m_RescaleFilter->SetOutputMinimum(outMin); m_RescaleFilter->SetOutputMaximum(outMax); m_RescaleFilter->UpdateOutputInformation(); SetParameterOutputImage("out", m_RescaleFilter->GetOutput()); } } MinMaxFilterType::Pointer m_MinMaxFilter; RescaleImageFilterType::Pointer m_RescaleFilter; DimensionalityReductionFilter::Pointer m_ForwardFilter; DimensionalityReductionFilter::Pointer m_InverseFilter; MatrixType m_TransformationMatrix; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::DimensionalityReduction) <commit_msg>ENH: remove useless call to c_str<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "itkImageToImageFilter.h" #include "otbMaximumAutocorrelationFactorImageFilter.h" #include "otbPCAImageFilter.h" #include "otbNAPCAImageFilter.h" #include "otbLocalActivityVectorImageFilter.h" #include "otbMaximumAutocorrelationFactorImageFilter.h" #include "otbFastICAImageFilter.h" #include "otbFastICAInternalOptimizerVectorImageFilter.h" //#include "otbVirtualDimensionality.h" #include "otbStreamingMinMaxVectorImageFilter.h" #include "otbVectorRescaleIntensityImageFilter.h" namespace otb { namespace Wrapper { class DimensionalityReduction: public Application { public: /** Standard class typedefs. */ typedef DimensionalityReduction Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; // Dimensionality reduction typedef typedef otb::MaximumAutocorrelationFactorImageFilter<FloatVectorImageType, FloatVectorImageType> MAFFilterType; typedef itk::ImageToImageFilter<FloatVectorImageType, FloatVectorImageType> DimensionalityReductionFilter; // Reduction dimensio filters typedef otb::PCAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD> PCAForwardFilterType; typedef otb::PCAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::INVERSE> PCAInverseFilterType; //typedef otb::PCAImageFilter< FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD > typedef otb::LocalActivityVectorImageFilter<FloatVectorImageType, FloatVectorImageType> NoiseFilterType; typedef otb::NAPCAImageFilter<FloatVectorImageType, FloatVectorImageType, NoiseFilterType, otb::Transform::FORWARD> NAPCAForwardFilterType; typedef otb::NAPCAImageFilter<FloatVectorImageType, FloatVectorImageType, NoiseFilterType, otb::Transform::INVERSE> NAPCAInverseFilterType; typedef otb::MaximumAutocorrelationFactorImageFilter<FloatVectorImageType, FloatVectorImageType> MAFForwardFilterType; typedef otb::FastICAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD> ICAForwardFilterType; typedef otb::FastICAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::INVERSE> ICAInverseFilterType; typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType> StreamingStatisticsVectorImageFilterType; typedef StreamingStatisticsVectorImageFilterType::MatrixObjectType::ComponentType MatrixType; //typedef otb::VirtualDimensionality<double> VDFilterType; // output rescale typedef otb::StreamingMinMaxVectorImageFilter<FloatVectorImageType> MinMaxFilterType; typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType> RescaleImageFilterType; /** Standard macro */ itkNewMacro(Self) ; itkTypeMacro(DimensionalityReduction, otb::Wrapper::Application) ; private: void DoInit() { SetName("DimensionalityReduction"); SetDescription("Perform Dimension reduction of the input image."); SetDocName("Dimensionality reduction"); SetDocLongDescription("Performs dimensionality reduction on input image. PCA,NA-PCA,MAF,ICA methods are available."); SetDocLimitations( "Though the inverse transform can be computed, this application only provides the forward transform for now."); SetDocAuthors("OTB-Team"); SetDocSeeAlso( "\"Kernel maximum autocorrelation factor and minimum noise fraction transformations,\" IEEE Transactions on Image Processing, vol. 20, no. 3, pp. 612-624, (2011)"); AddDocTag(Tags::DimensionReduction); AddDocTag(Tags::Filter); AddParameter(ParameterType_InputImage, "in", "Input Image"); SetParameterDescription("in", "The input image to apply dimensionality reduction."); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out", "output image. Components are ordered by decreasing eigenvalues."); AddParameter(ParameterType_Group, "rescale", "Rescale Output."); MandatoryOff("rescale"); // AddChoice("rescale.no","No rescale"); // AddChoice("rescale.minmax","rescale to min max value"); AddParameter(ParameterType_Float, "rescale.outmin", "Output min value"); AddParameter(ParameterType_Float, "rescale.outmax", "Output max value"); SetDefaultParameterFloat("rescale.outmin", 0.0); SetParameterDescription("rescale.outmin", "Minimum value of the output image."); SetDefaultParameterFloat("rescale.outmax", 255.0); SetParameterDescription("rescale.outmax", "Maximum value of the output image."); AddParameter(ParameterType_OutputImage, "outinv", " Inverse Output Image"); SetParameterDescription("outinv", "reconstruct output image."); MandatoryOff("outinv"); AddParameter(ParameterType_Choice, "method", "Algorithm"); SetParameterDescription("method", "Selection of the reduction dimension method."); AddChoice("method.pca", "PCA"); SetParameterDescription("method.pca", "Principal Component Analysis."); AddChoice("method.napca", "NA-PCA"); SetParameterDescription("method.napca", "Noise Adjusted Principal Component Analysis."); AddParameter(ParameterType_Int, "method.napca.radiusx", "Set the x radius of the sliding window."); SetMinimumParameterIntValue("method.napca.radiusx", 1); SetDefaultParameterInt("method.napca.radiusx", 1); AddParameter(ParameterType_Int, "method.napca.radiusy", "Set the y radius of the sliding window."); SetMinimumParameterIntValue("method.napca.radiusy", 1); SetDefaultParameterInt("method.napca.radiusy", 1); AddChoice("method.maf", "MAF"); SetParameterDescription("method.maf", "Maximum Autocorrelation Factor."); AddChoice("method.ica", "ICA"); SetParameterDescription("method.ica", "Independant Component Analysis."); AddParameter(ParameterType_Int, "method.ica.iter", "number of iterations "); SetMinimumParameterIntValue("method.ica.iter", 1); SetDefaultParameterInt("method.ica.iter", 20); MandatoryOff("method.ica.iter"); AddParameter(ParameterType_Float, "method.ica.mu", "Give the increment weight of W in [0, 1]"); SetMinimumParameterFloatValue("method.ica.mu", 0.); SetMaximumParameterFloatValue("method.ica.mu", 1.); SetDefaultParameterFloat("method.ica.mu", 1.); MandatoryOff("method.ica.mu"); //AddChoice("method.vd","virual Dimension"); //SetParameterDescription("method.vd","Virtual Dimension."); //MandatoryOff("method"); AddParameter(ParameterType_Int, "nbcomp", "Number of Components."); SetParameterDescription("nbcomp", "Number of relevant components kept. By default all components are kept."); SetDefaultParameterInt("nbcomp", 0); MandatoryOff("nbcomp"); SetMinimumParameterIntValue("nbcomp", 0); AddParameter(ParameterType_Empty, "normalize", "Normalize."); SetParameterDescription("normalize", "center AND reduce data before Dimensionality reduction."); MandatoryOff("normalize"); AddParameter(ParameterType_OutputFilename, "outmatrix", "Transformation matrix output"); SetParameterDescription("outmatrix", "Filename to store the transformation matrix (csv format)"); MandatoryOff("outmatrix"); // Doc example parameter settings SetDocExampleParameterValue("in", "cupriteSubHsi.tif"); SetDocExampleParameterValue("out", "FilterOutput.tif"); SetDocExampleParameterValue("method", "pca"); } void DoUpdateParameters() { } void DoExecute() { // Get Parameters int nbComp = GetParameterInt("nbcomp"); bool normalize = HasValue("normalize"); bool rescale = IsParameterEnabled("rescale"); bool invTransform = HasValue("outinv"); switch (GetParameterInt("method")) { // PCA Algorithm case 0: { otbAppLogDEBUG( << "PCA Algorithm "); PCAForwardFilterType::Pointer filter = PCAForwardFilterType::New(); m_ForwardFilter = filter; PCAInverseFilterType::Pointer invFilter = PCAInverseFilterType::New(); m_InverseFilter = invFilter; filter->SetInput(GetParameterFloatVectorImage("in")); filter->SetNumberOfPrincipalComponentsRequired(nbComp); filter->SetUseNormalization(normalize); m_ForwardFilter->Update(); if (invTransform) { invFilter->SetInput(m_ForwardFilter->GetOutput()); if (normalize) { otbAppLogINFO( << "Normalization MeanValue :"<<filter->GetMeanValues()<< "StdValue :" <<filter->GetStdDevValues() ); invFilter->SetMeanValues(filter->GetMeanValues()); invFilter->SetStdDevValues(filter->GetStdDevValues()); } invFilter->SetTransformationMatrix(filter->GetTransformationMatrix()); m_TransformationMatrix = invFilter->GetTransformationMatrix(); } m_TransformationMatrix = filter->GetTransformationMatrix(); break; } case 1: { otbAppLogDEBUG( << "NA-PCA Algorithm "); // NA-PCA unsigned int radiusX = static_cast<unsigned int> (GetParameterInt("method.napca.radiusx")); unsigned int radiusY = static_cast<unsigned int> (GetParameterInt("method.napca.radiusy")); // Noise filtering NoiseFilterType::RadiusType radius = { { radiusX, radiusY } }; NAPCAForwardFilterType::Pointer filter = NAPCAForwardFilterType::New(); m_ForwardFilter = filter; NAPCAInverseFilterType::Pointer invFilter = NAPCAInverseFilterType::New(); m_InverseFilter = invFilter; filter->SetInput(GetParameterFloatVectorImage("in")); filter->SetNumberOfPrincipalComponentsRequired(nbComp); filter->SetUseNormalization(normalize); filter->GetNoiseImageFilter()->SetRadius(radius); m_ForwardFilter->Update(); if (invTransform) { otbAppLogDEBUG( << "Compute Inverse Transform"); invFilter->SetInput(m_ForwardFilter->GetOutput()); invFilter->SetMeanValues(filter->GetMeanValues()); if (normalize) { invFilter->SetStdDevValues(filter->GetStdDevValues()); } invFilter->SetTransformationMatrix(filter->GetTransformationMatrix()); m_TransformationMatrix = invFilter->GetTransformationMatrix(); } m_TransformationMatrix = filter->GetTransformationMatrix(); break; } case 2: { otbAppLogDEBUG( << "MAF Algorithm "); MAFForwardFilterType::Pointer filter = MAFForwardFilterType::New(); m_ForwardFilter = filter; filter->SetInput(GetParameterFloatVectorImage("in")); m_ForwardFilter->Update(); otbAppLogINFO( << "V :"<<std::endl<<filter->GetV()<<"Auto-Correlation :"<<std::endl <<filter->GetAutoCorrelation() ); break; } case 3: { otbAppLogDEBUG( << "Fast ICA Algorithm "); unsigned int nbIterations = static_cast<unsigned int> (GetParameterInt("method.ica.iter")); double mu = static_cast<double> (GetParameterFloat("method.ica.mu")); ICAForwardFilterType::Pointer filter = ICAForwardFilterType::New(); m_ForwardFilter = filter; ICAInverseFilterType::Pointer invFilter = ICAInverseFilterType::New(); m_InverseFilter = invFilter; filter->SetInput(GetParameterFloatVectorImage("in")); filter->SetNumberOfPrincipalComponentsRequired(nbComp); filter->SetNumberOfIterations(nbIterations); filter->SetMu(mu); m_ForwardFilter->Update(); if (invTransform) { otbAppLogDEBUG( << "Compute Inverse Transform"); invFilter->SetInput(m_ForwardFilter->GetOutput()); if (normalize) { invFilter->SetMeanValues(filter->GetMeanValues()); invFilter->SetStdDevValues(filter->GetStdDevValues()); } invFilter->SetPCATransformationMatrix(filter->GetPCATransformationMatrix()); invFilter->SetTransformationMatrix(filter->GetTransformationMatrix()); } m_TransformationMatrix = filter->GetTransformationMatrix(); break; } /* case 4: { otbAppLogDEBUG( << "VD Algorithm"); break; }*/ default: { otbAppLogFATAL(<<"non defined method "<<GetParameterInt("method")<<std::endl); break; } return; } if (invTransform) { if (GetParameterInt("method") == 2) //MAF or VD { otbAppLogWARNING(<<"This application only provides the forward transform ."); } else SetParameterOutputImage("outinv", m_InverseFilter->GetOutput()); } //Write transformation matrix if (this->GetParameterString("outmatrix").size() != 0) { if (GetParameterInt("method") == 2) //MAF or VD { otbAppLogWARNING(<<"No transformation matrix available for MAF."); } else { //Write transformation matrix std::ofstream outFile; outFile.open(this->GetParameterString("outmatrix").c_str()); outFile << std::fixed; outFile.precision(10); outFile << m_TransformationMatrix; outFile.close(); } } if (!rescale) { SetParameterOutputImage("out", m_ForwardFilter->GetOutput()); } else { otbAppLogDEBUG( << "Rescaling " ) otbAppLogDEBUG( << "Starting Min/Max computation" ) m_MinMaxFilter = MinMaxFilterType::New(); m_MinMaxFilter->SetInput(m_ForwardFilter->GetOutput()); m_MinMaxFilter->GetStreamer()->SetNumberOfLinesStrippedStreaming(50); AddProcess(m_MinMaxFilter->GetStreamer(), "Min/Max computing"); m_MinMaxFilter->Update(); otbAppLogDEBUG( << "Min/Max computation done : min=" << m_MinMaxFilter->GetMinimum() << " max=" << m_MinMaxFilter->GetMaximum() ) FloatVectorImageType::PixelType inMin, inMax; m_RescaleFilter = RescaleImageFilterType::New(); m_RescaleFilter->SetInput(m_ForwardFilter->GetOutput()); m_RescaleFilter->SetInputMinimum(m_MinMaxFilter->GetMinimum()); m_RescaleFilter->SetInputMaximum(m_MinMaxFilter->GetMaximum()); FloatVectorImageType::PixelType outMin, outMax; outMin.SetSize(m_ForwardFilter->GetOutput()->GetNumberOfComponentsPerPixel()); outMax.SetSize(m_ForwardFilter->GetOutput()->GetNumberOfComponentsPerPixel()); outMin.Fill(GetParameterFloat("rescale.outmin")); outMax.Fill(GetParameterFloat("rescale.outmax")); m_RescaleFilter->SetOutputMinimum(outMin); m_RescaleFilter->SetOutputMaximum(outMax); m_RescaleFilter->UpdateOutputInformation(); SetParameterOutputImage("out", m_RescaleFilter->GetOutput()); } } MinMaxFilterType::Pointer m_MinMaxFilter; RescaleImageFilterType::Pointer m_RescaleFilter; DimensionalityReductionFilter::Pointer m_ForwardFilter; DimensionalityReductionFilter::Pointer m_InverseFilter; MatrixType m_TransformationMatrix; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::DimensionalityReduction) <|endoftext|>
<commit_before>// Copyright (c) 2012-2020 FRC Team 3512. All Rights Reserved. #include "Robot.hpp" #include <cmath> Robot::Robot() { autonSelector.AddAutoMethod("Bridge", std::bind(&Robot::AutonBridgeInit, this), std::bind(&Robot::AutonBridgePeriodic, this)); autonSelector.AddAutoMethod("Shoot", std::bind(&Robot::AutonShootInit, this), std::bind(&Robot::AutonShootPeriodic, this)); } void Robot::DisabledInit() { bridgeArm.Set(LockSolenoid::State::kRetracted); } void Robot::AutonomousInit() { autonTimer.Reset(); autonTimer.Start(); autonSelector.ExecAutonomousInit(); autonTimer.Stop(); } void Robot::TeleopInit() { bridgeArm.Set(LockSolenoid::State::kRetracted); } void Robot::RobotPeriodic() { shooter.Update(); } void Robot::AutonomousPeriodic() { autonSelector.ExecAutonomousPeriodic(); } void Robot::TeleopPeriodic() { // Aim if (std::abs(turretStick.GetX()) > 0.06) { // manual turret movement // Squaring gives finer control with a smaller joystick movement // while retaining max speed turretMotor.Set(-turretStick.GetX() * std::abs(turretStick.GetX())); } // Turns shooter on/off if (turretStick.GetRawButtonPressed(1)) { if (shooter.IsEnabled()) { shooter.Disable(); } else { shooter.Disable(); } } // Ball intake/conveyor if (turretStick.GetRawButton(6)) { lift.Set(frc::Relay::kForward); // move lift up } else if (turretStick.GetRawButton(7)) { lift.Set(frc::Relay::kReverse); // move lift down } else { lift.Set(frc::Relay::kOff); // turn off lift } // Bridge arm if (driveStick2.GetRawButtonPressed(1)) { auto armState = bridgeArm.Get(); /* Toggles state of bridge arm between Retracted and Deployed * (Doesn't toggle if the arm is transitioning) */ if (armState == LockSolenoid::State::kRetracted) { bridgeArm.Set(LockSolenoid::State::kDeployed); } else if (armState == LockSolenoid::State::kDeployed) { bridgeArm.Set(LockSolenoid::State::kRetracted); } } // Makes sure bridge arm completed transitioning between states bridgeArm.Update(); drivetrain.CurvatureDrive(driveStick1.GetY(), driveStick2.GetX(), driveStick2.GetRawButton(2)); } #ifndef RUNNING_FRC_TESTS int main() { return frc::StartRobot<Robot>(); } #endif <commit_msg>Use lambdas instead of std::bind()<commit_after>// Copyright (c) 2012-2020 FRC Team 3512. All Rights Reserved. #include "Robot.hpp" #include <cmath> Robot::Robot() { autonSelector.AddAutoMethod( "Bridge", [=] { AutonBridgeInit(); }, [=] { AutonBridgePeriodic(); }); autonSelector.AddAutoMethod( "Shoot", [=] { AutonShootInit(); }, [=] { AutonShootPeriodic(); }); } void Robot::DisabledInit() { bridgeArm.Set(LockSolenoid::State::kRetracted); } void Robot::AutonomousInit() { autonTimer.Reset(); autonTimer.Start(); autonSelector.ExecAutonomousInit(); autonTimer.Stop(); } void Robot::TeleopInit() { bridgeArm.Set(LockSolenoid::State::kRetracted); } void Robot::RobotPeriodic() { shooter.Update(); } void Robot::AutonomousPeriodic() { autonSelector.ExecAutonomousPeriodic(); } void Robot::TeleopPeriodic() { // Aim if (std::abs(turretStick.GetX()) > 0.06) { // manual turret movement // Squaring gives finer control with a smaller joystick movement // while retaining max speed turretMotor.Set(-turretStick.GetX() * std::abs(turretStick.GetX())); } // Turns shooter on/off if (turretStick.GetRawButtonPressed(1)) { if (shooter.IsEnabled()) { shooter.Disable(); } else { shooter.Disable(); } } // Ball intake/conveyor if (turretStick.GetRawButton(6)) { lift.Set(frc::Relay::kForward); // move lift up } else if (turretStick.GetRawButton(7)) { lift.Set(frc::Relay::kReverse); // move lift down } else { lift.Set(frc::Relay::kOff); // turn off lift } // Bridge arm if (driveStick2.GetRawButtonPressed(1)) { auto armState = bridgeArm.Get(); /* Toggles state of bridge arm between Retracted and Deployed * (Doesn't toggle if the arm is transitioning) */ if (armState == LockSolenoid::State::kRetracted) { bridgeArm.Set(LockSolenoid::State::kDeployed); } else if (armState == LockSolenoid::State::kDeployed) { bridgeArm.Set(LockSolenoid::State::kRetracted); } } // Makes sure bridge arm completed transitioning between states bridgeArm.Update(); drivetrain.CurvatureDrive(driveStick1.GetY(), driveStick2.GetX(), driveStick2.GetRawButton(2)); } #ifndef RUNNING_FRC_TESTS int main() { return frc::StartRobot<Robot>(); } #endif <|endoftext|>
<commit_before>#include <stdio.h> #include <string.h> #include <string> #include <jvmti.h> #include "globals.h" #include "profiler.h" static ConfigurationOptions* CONFIGURATION = new ConfigurationOptions(); static Profiler* prof; // This has to be here, or the VM turns off class loading events. // And AsyncGetCallTrace needs class loading events to be turned on! void JNICALL OnClassLoad(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jclass klass) { IMPLICITLY_USE(jvmti_env); IMPLICITLY_USE(jni_env); IMPLICITLY_USE(thread); IMPLICITLY_USE(klass); } // Calls GetClassMethods on a given class to force the creation of // jmethodIDs of it. void CreateJMethodIDsForClass(jvmtiEnv *jvmti, jclass klass) { jint method_count; JvmtiScopedPtr<jmethodID> methods(jvmti); jvmtiError e = jvmti->GetClassMethods(klass, &method_count, methods.GetRef()); if (e != JVMTI_ERROR_NONE && e != JVMTI_ERROR_CLASS_NOT_PREPARED) { // JVMTI_ERROR_CLASS_NOT_PREPARED is okay because some classes may // be loaded but not prepared at this point. JvmtiScopedPtr<char> ksig(jvmti); JVMTI_ERROR((jvmti->GetClassSignature(klass, ksig.GetRef(), NULL))); logError("Failed to create method IDs for methods in class %s with error %d ", ksig.Get(), e); } } void JNICALL OnVMInit(jvmtiEnv *jvmti, JNIEnv *jniEnv, jthread thread) { IMPLICITLY_USE(thread); // Forces the creation of jmethodIDs of the classes that had already // been loaded (eg java.lang.Object, java.lang.ClassLoader) and // OnClassPrepare() misses. jint class_count; JvmtiScopedPtr<jclass> classes(jvmti); JVMTI_ERROR((jvmti->GetLoadedClasses(&class_count, classes.GetRef()))); jclass *classList = classes.Get(); for (int i = 0; i < class_count; ++i) { jclass klass = classList[i]; CreateJMethodIDsForClass(jvmti, klass); } if (CONFIGURATION->start) prof->start(jniEnv); } void JNICALL OnClassPrepare(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jclass klass) { IMPLICITLY_USE(jni_env); IMPLICITLY_USE(thread); // We need to do this to "prime the pump", as it were -- make sure // that all of the methodIDs have been initialized internally, for // AsyncGetCallTrace. I imagine it slows down class loading a mite, // but honestly, how fast does class loading have to be? CreateJMethodIDsForClass(jvmti_env, klass); } void JNICALL OnVMDeath(jvmtiEnv *jvmti_env, JNIEnv *jni_env) { IMPLICITLY_USE(jvmti_env); IMPLICITLY_USE(jni_env); prof->stop(); } static bool PrepareJvmti(jvmtiEnv *jvmti) { // Set the list of permissions to do the various internal VM things // we want to do. jvmtiCapabilities caps; memset(&caps, 0, sizeof(caps)); caps.can_generate_all_class_hook_events = 1; caps.can_get_source_file_name = 1; caps.can_get_line_numbers = 1; caps.can_get_bytecodes = 1; caps.can_get_constant_pool = 1; jvmtiCapabilities all_caps; int error; if (JVMTI_ERROR_NONE == (error = jvmti->GetPotentialCapabilities(&all_caps))) { // This makes sure that if we need a capability, it is one of the // potential capabilities. The technique isn't wonderful, but it // is compact and as likely to be compatible between versions as // anything else. char *has = reinterpret_cast<char *>(&all_caps); const char *should_have = reinterpret_cast<const char *>(&caps); for (int i = 0; i < sizeof(all_caps); i++) { if ((should_have[i] != 0) && (has[i] == 0)) { return false; } } // This adds the capabilities. if ((error = jvmti->AddCapabilities(&caps)) != JVMTI_ERROR_NONE) { logError("Failed to add capabilities with error %d\n", error); return false; } } return true; } static bool RegisterJvmti(jvmtiEnv *jvmti) { // Create the list of callbacks to be called on given events. jvmtiEventCallbacks *callbacks = new jvmtiEventCallbacks(); memset(callbacks, 0, sizeof(jvmtiEventCallbacks)); callbacks->VMInit = &OnVMInit; callbacks->VMDeath = &OnVMDeath; callbacks->ClassLoad = &OnClassLoad; callbacks->ClassPrepare = &OnClassPrepare; JVMTI_ERROR_1( (jvmti->SetEventCallbacks(callbacks, sizeof(jvmtiEventCallbacks))), false); jvmtiEvent events[] = {JVMTI_EVENT_CLASS_LOAD, JVMTI_EVENT_CLASS_PREPARE, JVMTI_EVENT_VM_DEATH, JVMTI_EVENT_VM_INIT}; size_t num_events = sizeof(events) / sizeof(jvmtiEvent); // Enable the callbacks to be triggered when the events occur. // Events are enumerated in jvmstatagent.h for (int i = 0; i < num_events; i++) { JVMTI_ERROR_1( (jvmti->SetEventNotificationMode(JVMTI_ENABLE, events[i], NULL)), false); } return true; } static void parseArguments(char *options, ConfigurationOptions &configuration) { configuration.initializeDefaults(); char* next = options; for (char *key = options; next != NULL; key = next + 1) { char *value = strchr(key, '='); next = strchr(key, ','); if (value == NULL) { logError("No value for key %s\n", key); continue; } else { value++; if (strstr(key, "intervalMin") == key) { configuration.samplingIntervalMin = atoi(value); } else if (strstr(key, "intervalMax") == key) { configuration.samplingIntervalMax = atoi(value); } else if (strstr(key, "interval") == key) { configuration.samplingIntervalMin = configuration.samplingIntervalMax = atoi(value); } else if (strstr(key, "logPath") == key) { size_t size = (next == 0) ? strlen(key) : (size_t) (next - value); configuration.logFilePath = (char*) malloc(size * sizeof(char)); strncpy(configuration.logFilePath, value, size); } else if (strstr(key, "start") == key) { configuration.start = atoi(value); } else { logError("Unknown configuration option: %s\n", key); } } } } AGENTEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) { IMPLICITLY_USE(reserved); int err; jvmtiEnv *jvmti; parseArguments(options, *CONFIGURATION); if ((err = (jvm->GetEnv(reinterpret_cast<void **>(&jvmti), JVMTI_VERSION))) != JNI_OK) { logError("JVMTI initialisation Error %d\n", err); return 1; } /* JNIEnv *jniEnv; if ((err = (vm->GetEnv(reinterpret_cast<void **>(&jniEnv), JNI_VERSION_1_6))) != JNI_OK) { logError("JNI Error %d\n", err); return 1; } */ if (!PrepareJvmti(jvmti)) { logError("Failed to initialize JVMTI. Continuing...\n"); return 0; } if (!RegisterJvmti(jvmti)) { logError("Failed to enable JVMTI events. Continuing...\n"); // We fail hard here because we may have failed in the middle of // registering callbacks, which will leave the system in an // inconsistent state. return 1; } Asgct::SetAsgct(Accessors::GetJvmFunction<ASGCTType>("AsyncGetCallTrace")); prof = new Profiler(jvm, jvmti, CONFIGURATION); return 0; } AGENTEXPORT void JNICALL Agent_OnUnload(JavaVM *vm) { IMPLICITLY_USE(vm); } void bootstrapHandle(int signum, siginfo_t *info, void *context) { prof->handle(signum, info, context); } void logError(const char *__restrict format, ...) { va_list arg; va_start(arg, format); fprintf(stderr, format, arg); va_end(arg); } Profiler *getProfiler() { return prof; } <commit_msg>Use vprintf for logError<commit_after>#include <stdio.h> #include <string.h> #include <string> #include <jvmti.h> #include "globals.h" #include "profiler.h" static ConfigurationOptions* CONFIGURATION = new ConfigurationOptions(); static Profiler* prof; // This has to be here, or the VM turns off class loading events. // And AsyncGetCallTrace needs class loading events to be turned on! void JNICALL OnClassLoad(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jclass klass) { IMPLICITLY_USE(jvmti_env); IMPLICITLY_USE(jni_env); IMPLICITLY_USE(thread); IMPLICITLY_USE(klass); } // Calls GetClassMethods on a given class to force the creation of // jmethodIDs of it. void CreateJMethodIDsForClass(jvmtiEnv *jvmti, jclass klass) { jint method_count; JvmtiScopedPtr<jmethodID> methods(jvmti); jvmtiError e = jvmti->GetClassMethods(klass, &method_count, methods.GetRef()); if (e != JVMTI_ERROR_NONE && e != JVMTI_ERROR_CLASS_NOT_PREPARED) { // JVMTI_ERROR_CLASS_NOT_PREPARED is okay because some classes may // be loaded but not prepared at this point. JvmtiScopedPtr<char> ksig(jvmti); JVMTI_ERROR((jvmti->GetClassSignature(klass, ksig.GetRef(), NULL))); logError("Failed to create method IDs for methods in class %s with error %d ", ksig.Get(), e); } } void JNICALL OnVMInit(jvmtiEnv *jvmti, JNIEnv *jniEnv, jthread thread) { IMPLICITLY_USE(thread); // Forces the creation of jmethodIDs of the classes that had already // been loaded (eg java.lang.Object, java.lang.ClassLoader) and // OnClassPrepare() misses. jint class_count; JvmtiScopedPtr<jclass> classes(jvmti); JVMTI_ERROR((jvmti->GetLoadedClasses(&class_count, classes.GetRef()))); jclass *classList = classes.Get(); for (int i = 0; i < class_count; ++i) { jclass klass = classList[i]; CreateJMethodIDsForClass(jvmti, klass); } if (CONFIGURATION->start) prof->start(jniEnv); } void JNICALL OnClassPrepare(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jclass klass) { IMPLICITLY_USE(jni_env); IMPLICITLY_USE(thread); // We need to do this to "prime the pump", as it were -- make sure // that all of the methodIDs have been initialized internally, for // AsyncGetCallTrace. I imagine it slows down class loading a mite, // but honestly, how fast does class loading have to be? CreateJMethodIDsForClass(jvmti_env, klass); } void JNICALL OnVMDeath(jvmtiEnv *jvmti_env, JNIEnv *jni_env) { IMPLICITLY_USE(jvmti_env); IMPLICITLY_USE(jni_env); prof->stop(); } static bool PrepareJvmti(jvmtiEnv *jvmti) { // Set the list of permissions to do the various internal VM things // we want to do. jvmtiCapabilities caps; memset(&caps, 0, sizeof(caps)); caps.can_generate_all_class_hook_events = 1; caps.can_get_source_file_name = 1; caps.can_get_line_numbers = 1; caps.can_get_bytecodes = 1; caps.can_get_constant_pool = 1; jvmtiCapabilities all_caps; int error; if (JVMTI_ERROR_NONE == (error = jvmti->GetPotentialCapabilities(&all_caps))) { // This makes sure that if we need a capability, it is one of the // potential capabilities. The technique isn't wonderful, but it // is compact and as likely to be compatible between versions as // anything else. char *has = reinterpret_cast<char *>(&all_caps); const char *should_have = reinterpret_cast<const char *>(&caps); for (int i = 0; i < sizeof(all_caps); i++) { if ((should_have[i] != 0) && (has[i] == 0)) { return false; } } // This adds the capabilities. if ((error = jvmti->AddCapabilities(&caps)) != JVMTI_ERROR_NONE) { logError("Failed to add capabilities with error %d\n", error); return false; } } return true; } static bool RegisterJvmti(jvmtiEnv *jvmti) { // Create the list of callbacks to be called on given events. jvmtiEventCallbacks *callbacks = new jvmtiEventCallbacks(); memset(callbacks, 0, sizeof(jvmtiEventCallbacks)); callbacks->VMInit = &OnVMInit; callbacks->VMDeath = &OnVMDeath; callbacks->ClassLoad = &OnClassLoad; callbacks->ClassPrepare = &OnClassPrepare; JVMTI_ERROR_1( (jvmti->SetEventCallbacks(callbacks, sizeof(jvmtiEventCallbacks))), false); jvmtiEvent events[] = {JVMTI_EVENT_CLASS_LOAD, JVMTI_EVENT_CLASS_PREPARE, JVMTI_EVENT_VM_DEATH, JVMTI_EVENT_VM_INIT}; size_t num_events = sizeof(events) / sizeof(jvmtiEvent); // Enable the callbacks to be triggered when the events occur. // Events are enumerated in jvmstatagent.h for (int i = 0; i < num_events; i++) { JVMTI_ERROR_1( (jvmti->SetEventNotificationMode(JVMTI_ENABLE, events[i], NULL)), false); } return true; } static void parseArguments(char *options, ConfigurationOptions &configuration) { configuration.initializeDefaults(); char* next = options; for (char *key = options; next != NULL; key = next + 1) { char *value = strchr(key, '='); next = strchr(key, ','); if (value == NULL) { logError("No value for key %s\n", key); continue; } else { value++; if (strstr(key, "intervalMin") == key) { configuration.samplingIntervalMin = atoi(value); } else if (strstr(key, "intervalMax") == key) { configuration.samplingIntervalMax = atoi(value); } else if (strstr(key, "interval") == key) { configuration.samplingIntervalMin = configuration.samplingIntervalMax = atoi(value); } else if (strstr(key, "logPath") == key) { size_t size = (next == 0) ? strlen(key) : (size_t) (next - value); configuration.logFilePath = (char*) malloc(size * sizeof(char)); strncpy(configuration.logFilePath, value, size); } else if (strstr(key, "start") == key) { configuration.start = atoi(value); } else { logError("Unknown configuration option: %s\n", key); } } } } AGENTEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) { IMPLICITLY_USE(reserved); int err; jvmtiEnv *jvmti; parseArguments(options, *CONFIGURATION); if ((err = (jvm->GetEnv(reinterpret_cast<void **>(&jvmti), JVMTI_VERSION))) != JNI_OK) { logError("JVMTI initialisation Error %d\n", err); return 1; } /* JNIEnv *jniEnv; if ((err = (vm->GetEnv(reinterpret_cast<void **>(&jniEnv), JNI_VERSION_1_6))) != JNI_OK) { logError("JNI Error %d\n", err); return 1; } */ if (!PrepareJvmti(jvmti)) { logError("Failed to initialize JVMTI. Continuing...\n"); return 0; } if (!RegisterJvmti(jvmti)) { logError("Failed to enable JVMTI events. Continuing...\n"); // We fail hard here because we may have failed in the middle of // registering callbacks, which will leave the system in an // inconsistent state. return 1; } Asgct::SetAsgct(Accessors::GetJvmFunction<ASGCTType>("AsyncGetCallTrace")); prof = new Profiler(jvm, jvmti, CONFIGURATION); return 0; } AGENTEXPORT void JNICALL Agent_OnUnload(JavaVM *vm) { IMPLICITLY_USE(vm); } void bootstrapHandle(int signum, siginfo_t *info, void *context) { prof->handle(signum, info, context); } void logError(const char *__restrict format, ...) { va_list arg; va_start(arg, format); vfprintf(stderr, format, arg); va_end(arg); } Profiler *getProfiler() { return prof; } <|endoftext|>
<commit_before>/* * Copyright (c) 2011 Matt Fichman * * 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 "Environment.hpp" #include "Parser.hpp" #include "SemanticAnalyzer.hpp" #include "BasicBlockGenerator.hpp" #include "RegisterAllocator.hpp" #include "Intel64CodeGenerator.hpp" #include "BasicBlockPrinter.hpp" #include "DeadCodeEliminator.hpp" #include "CopyPropagator.hpp" #include "TreePrinter.hpp" #include "Machine.hpp" #include "Options.hpp" #include <iostream> int main(int argc, char** argv) { // Create a new empty environment to store the AST and symbols tables, and // set the options for compilation. Environment::Ptr env(new Environment()); Options(env, argc, argv); // Run the compiler. Output to a temporary file if the compiler will // continue on to another stage; otherwise, output the file directly. Parser::Ptr parser(new Parser(env)); SemanticAnalyzer::Ptr checker(new SemanticAnalyzer(env)); if (env->dump_ast()) { Stream::Ptr out(new Stream(env->output())); TreePrinter::Ptr print(new TreePrinter(env, out)); return env->errors() ? 0 : 1; } if (env->errors()) { return 1; } Machine::Ptr machine = Machine::intel64(); BasicBlockGenerator::Ptr generator(new BasicBlockGenerator(env, machine)); if (env->optimize()) { CopyPropagator::Ptr copy(new CopyPropagator(env)); DeadCodeEliminator::Ptr opt(new DeadCodeEliminator(env, machine)); } RegisterAllocator::Ptr alloc(new RegisterAllocator(env, machine)); if (env->dump_ir()) { Stream::Ptr out(new Stream(env->output())); BasicBlockPrinter::Ptr print(new BasicBlockPrinter(env, machine, out)); return 0; } std::string asm_file = env->assemble() ? tmpnam(0) : env->output(); Stream::Ptr out(new Stream(asm_file)); Intel64CodeGenerator::Ptr codegen(new Intel64CodeGenerator(env, out)); if (!env->assemble()) { return 0; } // Run the assembler. Output to a non-temp file if the compiler will stop // at the assembly stage std::string obj_file = env->link() ? tmpnam(0) : env->output(); std::stringstream ss; #if defined(WINDOWS) ss << "nasm -fobj64 " << asm_file << " -o " << obj_file; #elif defined(LINUX) ss << "nasm -felf64 " << asm_file << " -o " << obj_file; #elif defined(DARWIN) ss << "nasm -fmacho64 " << asm_file << " -o " << obj_file; #endif system(ss.str().c_str()); ss.str(""); if (!env->link()) { return 0; } // Run the linker. Always output to the given output file name. std::string exe_file = env->output(); #if defined(WINDOWS) ss << "link.exe " << obj_file << " /OUT:" << exe_file; #elif defined(LINUX) ss << "gcc -m64 " << obj_file << " -o " << exe_file; #elif defined(DARWIN) ss << "gcc " << obj_file << " -o " << exe_file; #endif for (int i = 0; i < env->libs(); i++) { #ifdef WINDOWS ss << env->lib(i) << ".lib"; #else ss << " -l" << env->lib(i); #endif } for (int i = 0; i < env->includes(); i++) { if (File::is_dir(env->include(i))) { #ifdef WINDOWS ss << "/L:" << env->include(i); #else ss << " -L" << env->include(i); #endif } } system(ss.str().c_str()); return 0; } <commit_msg>Another fix for the front end<commit_after>/* * Copyright (c) 2011 Matt Fichman * * 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 "Environment.hpp" #include "Parser.hpp" #include "SemanticAnalyzer.hpp" #include "BasicBlockGenerator.hpp" #include "RegisterAllocator.hpp" #include "Intel64CodeGenerator.hpp" #include "BasicBlockPrinter.hpp" #include "DeadCodeEliminator.hpp" #include "CopyPropagator.hpp" #include "TreePrinter.hpp" #include "Machine.hpp" #include "Options.hpp" #include <iostream> int main(int argc, char** argv) { // Create a new empty environment to store the AST and symbols tables, and // set the options for compilation. Environment::Ptr env(new Environment()); Options(env, argc, argv); // Run the compiler. Output to a temporary file if the compiler will // continue on to another stage; otherwise, output the file directly. Parser::Ptr parser(new Parser(env)); SemanticAnalyzer::Ptr checker(new SemanticAnalyzer(env)); if (env->dump_ast()) { Stream::Ptr out(new Stream(env->output())); TreePrinter::Ptr print(new TreePrinter(env, out)); return env->errors() ? 0 : 1; } if (env->errors()) { return 1; } Machine::Ptr machine = Machine::intel64(); BasicBlockGenerator::Ptr generator(new BasicBlockGenerator(env, machine)); if (env->optimize()) { CopyPropagator::Ptr copy(new CopyPropagator(env)); DeadCodeEliminator::Ptr opt(new DeadCodeEliminator(env, machine)); } RegisterAllocator::Ptr alloc(new RegisterAllocator(env, machine)); if (env->dump_ir()) { Stream::Ptr out(new Stream(env->output())); BasicBlockPrinter::Ptr print(new BasicBlockPrinter(env, machine, out)); return 0; } std::string asm_file = env->assemble() ? tmpnam(0) : env->output(); Stream::Ptr out(new Stream(asm_file)); Intel64CodeGenerator::Ptr codegen(new Intel64CodeGenerator(env, out)); if (!env->assemble()) { return 0; } // Run the assembler. Output to a non-temp file if the compiler will stop // at the assembly stage std::string obj_file = env->link() ? tmpnam(0) : env->output(); std::stringstream ss; #if defined(WINDOWS) ss << "nasm -fobj64 " << asm_file << " -o " << obj_file; #elif defined(LINUX) ss << "nasm -felf64 " << asm_file << " -o " << obj_file; #elif defined(DARWIN) ss << "nasm -fmacho64 " << asm_file << " -o " << obj_file; #endif system(ss.str().c_str()); ss.str(""); if (!env->link()) { return 0; } // Run the linker. Always output to the given output file name. std::string exe_file = env->output() == "-" ? "out" : env->output(); #if defined(WINDOWS) ss << "link.exe " << obj_file << " /OUT:" << exe_file << ".exe"; #elif defined(LINUX) ss << "gcc -m64 " << obj_file << " -o " << exe_file; #elif defined(DARWIN) ss << "gcc " << obj_file << " -o " << exe_file; #endif for (int i = 0; i < env->libs(); i++) { #ifdef WINDOWS ss << env->lib(i) << ".lib"; #else ss << " -l" << env->lib(i); #endif } for (int i = 0; i < env->includes(); i++) { if (File::is_dir(env->include(i))) { #ifdef WINDOWS ss << "/L:" << env->include(i); #else ss << " -L" << env->include(i); #endif } } system(ss.str().c_str()); return 0; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Achim Brandt //////////////////////////////////////////////////////////////////////////////// #include "HttpResponse.h" #include <velocypack/Builder.h> #include <velocypack/Dumper.h> #include <velocypack/Options.h> #include <velocypack/velocypack-aliases.h> #include "Basics/Exceptions.h" #include "Basics/StringBuffer.h" #include "Basics/StringUtils.h" #include "Basics/VPackStringBufferAdapter.h" #include "Basics/VelocyPackDumper.h" #include "Basics/tri-strings.h" #include "Meta/conversion.h" #include "Rest/GeneralRequest.h" using namespace arangodb; using namespace arangodb::basics; bool HttpResponse::HIDE_PRODUCT_HEADER = false; HttpResponse::HttpResponse(ResponseCode code) : GeneralResponse(code), _isHeadResponse(false), _body(TRI_UNKNOWN_MEM_ZONE, false), _bodySize(0) { _generateBody = false; _contentType = ContentType::TEXT; _connectionType = rest::CONNECTION_KEEP_ALIVE; if (_body.c_str() == nullptr) { // no buffer could be reserved. out of memory! THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY); } } void HttpResponse::reset(ResponseCode code) { _responseCode = code; _headers.clear(); _connectionType = rest::CONNECTION_KEEP_ALIVE; _contentType = ContentType::TEXT; _isHeadResponse = false; _body.clear(); _bodySize = 0; } void HttpResponse::setCookie(std::string const& name, std::string const& value, int lifeTimeSeconds, std::string const& path, std::string const& domain, bool secure, bool httpOnly) { std::unique_ptr<StringBuffer> buffer = std::make_unique<StringBuffer>(TRI_UNKNOWN_MEM_ZONE); std::string tmp = StringUtils::trim(name); buffer->appendText(tmp); buffer->appendChar('='); tmp = StringUtils::urlEncode(value); buffer->appendText(tmp); if (lifeTimeSeconds != 0) { time_t rawtime; time(&rawtime); if (lifeTimeSeconds > 0) { rawtime += lifeTimeSeconds; } else { rawtime = 1; } if (rawtime > 0) { struct tm* timeinfo; char buffer2[80]; timeinfo = gmtime(&rawtime); strftime(buffer2, 80, "%a, %d-%b-%Y %H:%M:%S %Z", timeinfo); buffer->appendText(TRI_CHAR_LENGTH_PAIR("; expires=")); buffer->appendText(buffer2); } } if (!path.empty()) { buffer->appendText(TRI_CHAR_LENGTH_PAIR("; path=")); buffer->appendText(path); } if (!domain.empty()) { buffer->appendText(TRI_CHAR_LENGTH_PAIR("; domain=")); buffer->appendText(domain); } if (secure) { buffer->appendText(TRI_CHAR_LENGTH_PAIR("; secure")); } if (httpOnly) { buffer->appendText(TRI_CHAR_LENGTH_PAIR("; HttpOnly")); } _cookies.emplace_back(buffer->c_str()); } void HttpResponse::headResponse(size_t size) { _body.clear(); _isHeadResponse = true; _bodySize = size; } size_t HttpResponse::bodySize() const { if (_isHeadResponse) { return _bodySize; } return _body.length(); } void HttpResponse::writeHeader(StringBuffer* output) { output->appendText(TRI_CHAR_LENGTH_PAIR("HTTP/1.1 ")); output->appendText(responseString(_responseCode)); output->appendText("\r\n", 2); bool seenServerHeader = false; bool seenConnectionHeader = false; bool seenTransferEncodingHeader = false; std::string transferEncoding; for (auto const& it : _headers) { std::string const& key = it.first; size_t const keyLength = key.size(); // ignore content-length if (keyLength == 14 && key[0] == 'c' && memcmp(key.c_str(), "content-length", keyLength) == 0) { continue; } // save transfer encoding if (keyLength == 17 && key[0] == 't' && memcmp(key.c_str(), "transfer-encoding", keyLength) == 0) { seenTransferEncodingHeader = true; transferEncoding = it.second; continue; } if (keyLength == 6 && key[0] == 's' && memcmp(key.c_str(), "server", keyLength) == 0) { // this ensures we don't print two "Server" headers seenServerHeader = true; // go on and use the user-defined "Server" header value } else if (keyLength == 10 && key[0] == 'c' && memcmp(key.c_str(), "connection", keyLength) == 0) { // this ensures we don't print two "Connection" headers seenConnectionHeader = true; // go on and use the user-defined "Connection" header value } // reserve enough space for header name + ": " + value + "\r\n" if (output->reserve(keyLength + 2 + it.second.size() + 2) != TRI_ERROR_NO_ERROR) { THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY); } char const* p = key.c_str(); char const* end = p + keyLength; int capState = 1; while (p < end) { if (capState == 1) { // upper case output->appendCharUnsafe(::toupper(*p)); capState = 0; } else if (capState == 0) { // normal case output->appendCharUnsafe(::tolower(*p)); if (*p == '-') { capState = 1; } else if (*p == ':') { capState = 2; } } else { // output as is output->appendCharUnsafe(*p); } ++p; } output->appendTextUnsafe(": ", 2); output->appendTextUnsafe(it.second); output->appendTextUnsafe("\r\n", 2); } // add "Server" response header if (!seenServerHeader && !HIDE_PRODUCT_HEADER) { output->appendText("Server: ArangoDB\r\n"); } // add "Connection" response header if (!seenConnectionHeader) { switch (_connectionType) { case rest::ConnectionType::CONNECTION_KEEP_ALIVE: output->appendText(TRI_CHAR_LENGTH_PAIR("Connection: Keep-Alive\r\n")); break; case rest::ConnectionType::CONNECTION_CLOSE: output->appendText(TRI_CHAR_LENGTH_PAIR("Connection: Close\r\n")); break; case rest::ConnectionType::CONNECTION_NONE: output->appendText(TRI_CHAR_LENGTH_PAIR("Connection: \r\n")); break; } } // add "Content-Type" header switch (_contentType) { case ContentType::UNSET: case ContentType::JSON: output->appendText(TRI_CHAR_LENGTH_PAIR( "Content-Type: application/json; charset=utf-8\r\n")); break; case ContentType::VPACK: output->appendText( TRI_CHAR_LENGTH_PAIR("Content-Type: application/x-velocypack\r\n")); break; case ContentType::TEXT: output->appendText( TRI_CHAR_LENGTH_PAIR("Content-Type: text/plain; charset=utf-8\r\n")); break; case ContentType::HTML: output->appendText( TRI_CHAR_LENGTH_PAIR("Content-Type: text/html; charset=utf-8\r\n")); break; case ContentType::DUMP: output->appendText(TRI_CHAR_LENGTH_PAIR( "Content-Type: application/x-arango-dump; charset=utf-8\r\n")); break; case ContentType::CUSTOM: { // intentionally don't print anything here // the header should have been in _headers already, and should have been // handled above } } for (auto const& it : _cookies) { output->appendText(TRI_CHAR_LENGTH_PAIR("Set-Cookie: ")); output->appendText(it); output->appendText("\r\n", 2); } if (seenTransferEncodingHeader && transferEncoding == "chunked") { output->appendText( TRI_CHAR_LENGTH_PAIR("Transfer-Encoding: chunked\r\n\r\n")); } else { if (seenTransferEncodingHeader) { output->appendText(TRI_CHAR_LENGTH_PAIR("Transfer-Encoding: ")); output->appendText(transferEncoding); output->appendText("\r\n", 2); } output->appendText(TRI_CHAR_LENGTH_PAIR("Content-Length: ")); if (_isHeadResponse) { // From http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13 // // 14.13 Content-Length // // The Content-Length entity-header field indicates the size of the // entity-body, // in decimal number of OCTETs, sent to the recipient or, in the case of // the HEAD method, // the size of the entity-body that would have been sent had the request // been a GET. output->appendInteger(_bodySize); } else { output->appendInteger(_body.length()); } output->appendText("\r\n\r\n", 4); } // end of header, body to follow } void HttpResponse::addPayloadPostHook( VPackSlice const& slice, VPackOptions const* options = &VPackOptions::Options::Defaults, bool resolveExternals = true, bool bodySkipped = false) { VPackSlice const* slicePtr; if (!bodySkipped) { // we have Probably resolved externals TRI_ASSERT(!_vpackPayloads.empty()); VPackSlice tmpSlice = VPackSlice(_vpackPayloads.front().data()); slicePtr = &tmpSlice; } else { slicePtr = &slice; } switch (_contentType) { case rest::ContentType::VPACK: { size_t length = static_cast<size_t>(slicePtr->byteSize()); if (_generateBody) { _body.appendText(slicePtr->startAs<const char>(), length); } else { headResponse(length); } break; } default: { setContentType(rest::ContentType::JSON); if (_generateBody) { arangodb::basics::VelocyPackDumper dumper(&_body, options); dumper.dumpValue(*slicePtr); } else { // TODO can we optimize this? // Just dump some where else to find real length StringBuffer tmp(TRI_UNKNOWN_MEM_ZONE, false); // convert object to string VPackStringBufferAdapter buffer(tmp.stringBuffer()); // usual dumping - but not to the response body VPackDumper dumper(&buffer, options); dumper.dump(*slicePtr); headResponse(tmp.length()); } } } } <commit_msg>fix invalid pointer<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Achim Brandt //////////////////////////////////////////////////////////////////////////////// #include "HttpResponse.h" #include <velocypack/Builder.h> #include <velocypack/Dumper.h> #include <velocypack/Options.h> #include <velocypack/velocypack-aliases.h> #include "Basics/Exceptions.h" #include "Basics/StringBuffer.h" #include "Basics/StringUtils.h" #include "Basics/VPackStringBufferAdapter.h" #include "Basics/VelocyPackDumper.h" #include "Basics/tri-strings.h" #include "Meta/conversion.h" #include "Rest/GeneralRequest.h" using namespace arangodb; using namespace arangodb::basics; bool HttpResponse::HIDE_PRODUCT_HEADER = false; HttpResponse::HttpResponse(ResponseCode code) : GeneralResponse(code), _isHeadResponse(false), _body(TRI_UNKNOWN_MEM_ZONE, false), _bodySize(0) { _generateBody = false; _contentType = ContentType::TEXT; _connectionType = rest::CONNECTION_KEEP_ALIVE; if (_body.c_str() == nullptr) { // no buffer could be reserved. out of memory! THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY); } } void HttpResponse::reset(ResponseCode code) { _responseCode = code; _headers.clear(); _connectionType = rest::CONNECTION_KEEP_ALIVE; _contentType = ContentType::TEXT; _isHeadResponse = false; _body.clear(); _bodySize = 0; } void HttpResponse::setCookie(std::string const& name, std::string const& value, int lifeTimeSeconds, std::string const& path, std::string const& domain, bool secure, bool httpOnly) { std::unique_ptr<StringBuffer> buffer = std::make_unique<StringBuffer>(TRI_UNKNOWN_MEM_ZONE); std::string tmp = StringUtils::trim(name); buffer->appendText(tmp); buffer->appendChar('='); tmp = StringUtils::urlEncode(value); buffer->appendText(tmp); if (lifeTimeSeconds != 0) { time_t rawtime; time(&rawtime); if (lifeTimeSeconds > 0) { rawtime += lifeTimeSeconds; } else { rawtime = 1; } if (rawtime > 0) { struct tm* timeinfo; char buffer2[80]; timeinfo = gmtime(&rawtime); strftime(buffer2, 80, "%a, %d-%b-%Y %H:%M:%S %Z", timeinfo); buffer->appendText(TRI_CHAR_LENGTH_PAIR("; expires=")); buffer->appendText(buffer2); } } if (!path.empty()) { buffer->appendText(TRI_CHAR_LENGTH_PAIR("; path=")); buffer->appendText(path); } if (!domain.empty()) { buffer->appendText(TRI_CHAR_LENGTH_PAIR("; domain=")); buffer->appendText(domain); } if (secure) { buffer->appendText(TRI_CHAR_LENGTH_PAIR("; secure")); } if (httpOnly) { buffer->appendText(TRI_CHAR_LENGTH_PAIR("; HttpOnly")); } _cookies.emplace_back(buffer->c_str()); } void HttpResponse::headResponse(size_t size) { _body.clear(); _isHeadResponse = true; _bodySize = size; } size_t HttpResponse::bodySize() const { if (_isHeadResponse) { return _bodySize; } return _body.length(); } void HttpResponse::writeHeader(StringBuffer* output) { output->appendText(TRI_CHAR_LENGTH_PAIR("HTTP/1.1 ")); output->appendText(responseString(_responseCode)); output->appendText("\r\n", 2); bool seenServerHeader = false; bool seenConnectionHeader = false; bool seenTransferEncodingHeader = false; std::string transferEncoding; for (auto const& it : _headers) { std::string const& key = it.first; size_t const keyLength = key.size(); // ignore content-length if (keyLength == 14 && key[0] == 'c' && memcmp(key.c_str(), "content-length", keyLength) == 0) { continue; } // save transfer encoding if (keyLength == 17 && key[0] == 't' && memcmp(key.c_str(), "transfer-encoding", keyLength) == 0) { seenTransferEncodingHeader = true; transferEncoding = it.second; continue; } if (keyLength == 6 && key[0] == 's' && memcmp(key.c_str(), "server", keyLength) == 0) { // this ensures we don't print two "Server" headers seenServerHeader = true; // go on and use the user-defined "Server" header value } else if (keyLength == 10 && key[0] == 'c' && memcmp(key.c_str(), "connection", keyLength) == 0) { // this ensures we don't print two "Connection" headers seenConnectionHeader = true; // go on and use the user-defined "Connection" header value } // reserve enough space for header name + ": " + value + "\r\n" if (output->reserve(keyLength + 2 + it.second.size() + 2) != TRI_ERROR_NO_ERROR) { THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY); } char const* p = key.c_str(); char const* end = p + keyLength; int capState = 1; while (p < end) { if (capState == 1) { // upper case output->appendCharUnsafe(::toupper(*p)); capState = 0; } else if (capState == 0) { // normal case output->appendCharUnsafe(::tolower(*p)); if (*p == '-') { capState = 1; } else if (*p == ':') { capState = 2; } } else { // output as is output->appendCharUnsafe(*p); } ++p; } output->appendTextUnsafe(": ", 2); output->appendTextUnsafe(it.second); output->appendTextUnsafe("\r\n", 2); } // add "Server" response header if (!seenServerHeader && !HIDE_PRODUCT_HEADER) { output->appendText("Server: ArangoDB\r\n"); } // add "Connection" response header if (!seenConnectionHeader) { switch (_connectionType) { case rest::ConnectionType::CONNECTION_KEEP_ALIVE: output->appendText(TRI_CHAR_LENGTH_PAIR("Connection: Keep-Alive\r\n")); break; case rest::ConnectionType::CONNECTION_CLOSE: output->appendText(TRI_CHAR_LENGTH_PAIR("Connection: Close\r\n")); break; case rest::ConnectionType::CONNECTION_NONE: output->appendText(TRI_CHAR_LENGTH_PAIR("Connection: \r\n")); break; } } // add "Content-Type" header switch (_contentType) { case ContentType::UNSET: case ContentType::JSON: output->appendText(TRI_CHAR_LENGTH_PAIR( "Content-Type: application/json; charset=utf-8\r\n")); break; case ContentType::VPACK: output->appendText( TRI_CHAR_LENGTH_PAIR("Content-Type: application/x-velocypack\r\n")); break; case ContentType::TEXT: output->appendText( TRI_CHAR_LENGTH_PAIR("Content-Type: text/plain; charset=utf-8\r\n")); break; case ContentType::HTML: output->appendText( TRI_CHAR_LENGTH_PAIR("Content-Type: text/html; charset=utf-8\r\n")); break; case ContentType::DUMP: output->appendText(TRI_CHAR_LENGTH_PAIR( "Content-Type: application/x-arango-dump; charset=utf-8\r\n")); break; case ContentType::CUSTOM: { // intentionally don't print anything here // the header should have been in _headers already, and should have been // handled above } } for (auto const& it : _cookies) { output->appendText(TRI_CHAR_LENGTH_PAIR("Set-Cookie: ")); output->appendText(it); output->appendText("\r\n", 2); } if (seenTransferEncodingHeader && transferEncoding == "chunked") { output->appendText( TRI_CHAR_LENGTH_PAIR("Transfer-Encoding: chunked\r\n\r\n")); } else { if (seenTransferEncodingHeader) { output->appendText(TRI_CHAR_LENGTH_PAIR("Transfer-Encoding: ")); output->appendText(transferEncoding); output->appendText("\r\n", 2); } output->appendText(TRI_CHAR_LENGTH_PAIR("Content-Length: ")); if (_isHeadResponse) { // From http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13 // // 14.13 Content-Length // // The Content-Length entity-header field indicates the size of the // entity-body, // in decimal number of OCTETs, sent to the recipient or, in the case of // the HEAD method, // the size of the entity-body that would have been sent had the request // been a GET. output->appendInteger(_bodySize); } else { output->appendInteger(_body.length()); } output->appendText("\r\n\r\n", 4); } // end of header, body to follow } void HttpResponse::addPayloadPostHook( VPackSlice const& slice, VPackOptions const* options = &VPackOptions::Options::Defaults, bool resolveExternals = true, bool bodySkipped = false) { VPackSlice const* slicePtr; VPackSlice tmpSlice; if (!bodySkipped) { // we have Probably resolved externals TRI_ASSERT(!_vpackPayloads.empty()); tmpSlice = VPackSlice(_vpackPayloads.front().data()); slicePtr = &tmpSlice; } else { slicePtr = &slice; } switch (_contentType) { case rest::ContentType::VPACK: { size_t length = static_cast<size_t>(slicePtr->byteSize()); if (_generateBody) { _body.appendText(slicePtr->startAs<const char>(), length); } else { headResponse(length); } break; } default: { setContentType(rest::ContentType::JSON); if (_generateBody) { arangodb::basics::VelocyPackDumper dumper(&_body, options); dumper.dumpValue(*slicePtr); } else { // TODO can we optimize this? // Just dump some where else to find real length StringBuffer tmp(TRI_UNKNOWN_MEM_ZONE, false); // convert object to string VPackStringBufferAdapter buffer(tmp.stringBuffer()); // usual dumping - but not to the response body VPackDumper dumper(&buffer, options); dumper.dump(*slicePtr); headResponse(tmp.length()); } } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * 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. */ #ifndef __MEM_ADDR_MAPPER_HH__ #define __MEM_ADDR_MAPPER_HH__ #include "mem/port.hh" #include "params/AddrMapper.hh" #include "params/RangeAddrMapper.hh" #include "sim/sim_object.hh" /** * An address mapper changes the packet addresses in going from the * response port side of the mapper to the request port side. When the * response port is queried for the address ranges, it also performs the * necessary range updates. Note that snoop requests that travel from * the request port (i.e. the memory side) to the response port are * currently not modified. */ class AddrMapper : public SimObject { public: AddrMapper(const AddrMapperParams &params); virtual ~AddrMapper() { } Port &getPort(const std::string &if_name, PortID idx=InvalidPortID) override; void init() override; protected: /** * This function does the actual remapping of one address to another. * It is pure virtual in this case to to allow any implementation * required. * @param addr the address to remap * @return the new address (can be unchanged) */ virtual Addr remapAddr(Addr addr) const = 0; class AddrMapperSenderState : public Packet::SenderState { public: /** * Construct a new sender state to remember the original address. * * @param _origAddr Address before remapping */ AddrMapperSenderState(Addr _origAddr) : origAddr(_origAddr) { } /** Destructor */ ~AddrMapperSenderState() { } /** The original address the packet was destined for */ Addr origAddr; }; class MapperRequestPort : public RequestPort { public: MapperRequestPort(const std::string& _name, AddrMapper& _mapper) : RequestPort(_name, &_mapper), mapper(_mapper) { } protected: void recvFunctionalSnoop(PacketPtr pkt) { mapper.recvFunctionalSnoop(pkt); } Tick recvAtomicSnoop(PacketPtr pkt) { return mapper.recvAtomicSnoop(pkt); } bool recvTimingResp(PacketPtr pkt) { return mapper.recvTimingResp(pkt); } void recvTimingSnoopReq(PacketPtr pkt) { mapper.recvTimingSnoopReq(pkt); } void recvRangeChange() { mapper.recvRangeChange(); } bool isSnooping() const { return mapper.isSnooping(); } void recvReqRetry() { mapper.recvReqRetry(); } private: AddrMapper& mapper; }; /** Instance of request port, facing the memory side */ MapperRequestPort memSidePort; class MapperResponsePort : public ResponsePort { public: MapperResponsePort(const std::string& _name, AddrMapper& _mapper) : ResponsePort(_name, &_mapper), mapper(_mapper) { } protected: void recvFunctional(PacketPtr pkt) { mapper.recvFunctional(pkt); } Tick recvAtomic(PacketPtr pkt) { return mapper.recvAtomic(pkt); } bool recvTimingReq(PacketPtr pkt) { return mapper.recvTimingReq(pkt); } bool recvTimingSnoopResp(PacketPtr pkt) { return mapper.recvTimingSnoopResp(pkt); } AddrRangeList getAddrRanges() const { return mapper.getAddrRanges(); } void recvRespRetry() { mapper.recvRespRetry(); } private: AddrMapper& mapper; }; /** Instance of response port, i.e. on the CPU side */ MapperResponsePort cpuSidePort; void recvFunctional(PacketPtr pkt); void recvFunctionalSnoop(PacketPtr pkt); Tick recvAtomic(PacketPtr pkt); Tick recvAtomicSnoop(PacketPtr pkt); bool recvTimingReq(PacketPtr pkt); bool recvTimingResp(PacketPtr pkt); void recvTimingSnoopReq(PacketPtr pkt); bool recvTimingSnoopResp(PacketPtr pkt); virtual AddrRangeList getAddrRanges() const = 0; bool isSnooping() const; void recvReqRetry(); void recvRespRetry(); void recvRangeChange(); }; /** * Range address mapper that maps a set of original ranges to a set of * remapped ranges, where a specific range is of the same size * (original and remapped), only with an offset. It's useful for cases * where memory is mapped to two different locations */ class RangeAddrMapper : public AddrMapper { public: RangeAddrMapper(const RangeAddrMapperParams &p); ~RangeAddrMapper() { } AddrRangeList getAddrRanges() const; protected: /** * This contains a list of ranges the should be remapped. It must * be the exact same length as remappedRanges which describes what * manipulation should be done to each range. */ std::vector<AddrRange> originalRanges; /** * This contains a list of ranges that addresses should be * remapped to. See the description for originalRanges above */ std::vector<AddrRange> remappedRanges; Addr remapAddr(Addr addr) const; }; #endif //__MEM_ADDR_MAPPER_HH__ <commit_msg>mem: Fix style in addr_mapper.hh.<commit_after>/* * Copyright (c) 2012 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * 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. */ #ifndef __MEM_ADDR_MAPPER_HH__ #define __MEM_ADDR_MAPPER_HH__ #include "mem/port.hh" #include "params/AddrMapper.hh" #include "params/RangeAddrMapper.hh" #include "sim/sim_object.hh" /** * An address mapper changes the packet addresses in going from the * response port side of the mapper to the request port side. When the * response port is queried for the address ranges, it also performs the * necessary range updates. Note that snoop requests that travel from * the request port (i.e. the memory side) to the response port are * currently not modified. */ class AddrMapper : public SimObject { public: AddrMapper(const AddrMapperParams &params); virtual ~AddrMapper() = default; Port &getPort(const std::string &if_name, PortID idx=InvalidPortID) override; void init() override; protected: /** * This function does the actual remapping of one address to another. * It is pure virtual in this case to to allow any implementation * required. * @param addr the address to remap * @return the new address (can be unchanged) */ virtual Addr remapAddr(Addr addr) const = 0; class AddrMapperSenderState : public Packet::SenderState { public: /** * Construct a new sender state to remember the original address. * * @param _origAddr Address before remapping */ AddrMapperSenderState(Addr _origAddr) : origAddr(_origAddr) {} /** Destructor */ ~AddrMapperSenderState() {} /** The original address the packet was destined for */ Addr origAddr; }; class MapperRequestPort : public RequestPort { public: MapperRequestPort(const std::string& _name, AddrMapper& _mapper) : RequestPort(_name, &_mapper), mapper(_mapper) { } protected: void recvFunctionalSnoop(PacketPtr pkt) override { mapper.recvFunctionalSnoop(pkt); } Tick recvAtomicSnoop(PacketPtr pkt) override { return mapper.recvAtomicSnoop(pkt); } bool recvTimingResp(PacketPtr pkt) override { return mapper.recvTimingResp(pkt); } void recvTimingSnoopReq(PacketPtr pkt) override { mapper.recvTimingSnoopReq(pkt); } void recvRangeChange() override { mapper.recvRangeChange(); } bool isSnooping() const override { return mapper.isSnooping(); } void recvReqRetry() override { mapper.recvReqRetry(); } private: AddrMapper& mapper; }; /** Instance of request port, facing the memory side */ MapperRequestPort memSidePort; class MapperResponsePort : public ResponsePort { public: MapperResponsePort(const std::string& _name, AddrMapper& _mapper) : ResponsePort(_name, &_mapper), mapper(_mapper) {} protected: void recvFunctional(PacketPtr pkt) override { mapper.recvFunctional(pkt); } Tick recvAtomic(PacketPtr pkt) override { return mapper.recvAtomic(pkt); } bool recvTimingReq(PacketPtr pkt) override { return mapper.recvTimingReq(pkt); } bool recvTimingSnoopResp(PacketPtr pkt) override { return mapper.recvTimingSnoopResp(pkt); } AddrRangeList getAddrRanges() const override { return mapper.getAddrRanges(); } void recvRespRetry() override { mapper.recvRespRetry(); } private: AddrMapper& mapper; }; /** Instance of response port, i.e. on the CPU side */ MapperResponsePort cpuSidePort; void recvFunctional(PacketPtr pkt); void recvFunctionalSnoop(PacketPtr pkt); Tick recvAtomic(PacketPtr pkt); Tick recvAtomicSnoop(PacketPtr pkt); bool recvTimingReq(PacketPtr pkt); bool recvTimingResp(PacketPtr pkt); void recvTimingSnoopReq(PacketPtr pkt); bool recvTimingSnoopResp(PacketPtr pkt); virtual AddrRangeList getAddrRanges() const = 0; bool isSnooping() const; void recvReqRetry(); void recvRespRetry(); void recvRangeChange(); }; /** * Range address mapper that maps a set of original ranges to a set of * remapped ranges, where a specific range is of the same size * (original and remapped), only with an offset. It's useful for cases * where memory is mapped to two different locations */ class RangeAddrMapper : public AddrMapper { public: RangeAddrMapper(const RangeAddrMapperParams &p); ~RangeAddrMapper() = default; AddrRangeList getAddrRanges() const override; protected: /** * This contains a list of ranges the should be remapped. It must * be the exact same length as remappedRanges which describes what * manipulation should be done to each range. */ std::vector<AddrRange> originalRanges; /** * This contains a list of ranges that addresses should be * remapped to. See the description for originalRanges above */ std::vector<AddrRange> remappedRanges; Addr remapAddr(Addr addr) const override; }; #endif //__MEM_ADDR_MAPPER_HH__ <|endoftext|>
<commit_before>AliAnalysisTaskSubJetFraction* AddTaskAliAnalysisTaskSubJetFraction(const char * njetsData, //data jets const char * njetsTrue, //Pyhthia Particle Level const char * njetsDet, const char * njetsHybridUs, const char * njetsHybridS, const Double_t R, const char * nrhoBase, const char * ntracksData, const char * ntracksTrue, const char * ntracksDet, const char * ntracksHybridUs, const char * ntracksHybridS, const char * nclusters, const char *type, const char *CentEst, Double_t fSharedFractionPtMin, Int_t SubJetAlgorithm, Float_t SubJetRadius, Float_t SubJetMinPt, Int_t pSel, TString trigClass = "", TString kEmcalTriggers = "", TString tag = "", AliAnalysisTaskSubJetFraction::JetShapeType jetShapeType, AliAnalysisTaskSubJetFraction::JetShapeSub jetShapeSub, AliAnalysisTaskSubJetFraction::JetSelectionType jetSelection, Float_t minpTHTrigger =0., Float_t maxpTHTrigger =0., AliAnalysisTaskSubJetFraction::DerivSubtrOrder derivSubtrOrder = 0 ) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskAliAnalysisTaskSubJetFraction","No analysis manager found."); return 0; } Bool_t ismc=kFALSE; ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE; // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AliAnalysisTaskSubJetFraction", "This task requires an input event handler"); return NULL; } if (jetShapeType==AliAnalysisTaskSubJetFraction::kData || jetShapeType==AliAnalysisTaskSubJetFraction::kSim) TString wagonName = Form("AliAnalysisTaskSubJetFraction_%s_TC%s%s",njetsData,trigClass.Data(),tag.Data()); if (jetShapeType==AliAnalysisTaskSubJetFraction::kTrue || jetShapeType==AliAnalysisTaskSubJetFraction::kTrueDet || jetShapeType==AliAnalysisTaskSubJetFraction::kGenOnTheFly) TString wagonName = Form("AliAnalysisTaskSubJetFraction_%s_TC%s%s",njetsTrue,trigClass.Data(),tag.Data()); if (jetShapeType==AliAnalysisTaskSubJetFraction::kDetEmbPart) TString wagonName = Form("AliAnalysisTaskSubJetFraction_%s_TC%s%s",njetsHybridS,trigClass.Data(),tag.Data()); //Configure jet tagger task AliAnalysisTaskSubJetFraction *task = new AliAnalysisTaskSubJetFraction(wagonName.Data()); task->SetNCentBins(4); task->SetJetShapeType(jetShapeType); task->SetJetShapeSub(jetShapeSub); task->SetJetSelection(jetSelection); task->SetSubJetAlgorithm(SubJetAlgorithm); task->SetSubJetRadius(SubJetRadius); task->SetSubJetMinPt(SubJetMinPt); task->SetJetRadius(R); task->SetSharedFractionPtMin(fSharedFractionPtMin); task->SetDerivativeSubtractionOrder(derivSubtrOrder); if (jetSelection == AliAnalysisTaskSubJetFraction::kRecoil) task->SetPtTriggerSelections(minpTHTrigger, maxpTHTrigger); // TString thename(njetsBase); //if(thename.Contains("Sub")) task->SetIsConstSub(kTRUE); //task->SetVzRange(-10.,10.); AliParticleContainer *trackContData=0x0; AliParticleContainer *trackContDet=0x0; if (jetShapeSub == AliAnalysisTaskSubJetFraction::kConstSub){ trackContData = task->AddParticleContainer(ntracksData); trackContDet = task->AddParticleContainer(ntracksDet); } else{ trackContData = task->AddTrackContainer(ntracksData); trackContDet = task->AddTrackContainer(ntracksDet); } AliParticleContainer *trackContTrue = task->AddMCParticleContainer(ntracksTrue); AliParticleContainer *trackContHybridUs = task->AddParticleContainer(ntracksHybridUs); AliParticleContainer *trackContHybridS = task->AddParticleContainer(ntracksHybridS); AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters); AliJetContainer *JetContData=0x0; AliJetContainer *JetContTrue=0x0; AliJetContainer *JetContDet=0x0; AliJetContainer *JetContHybridUs=0x0; AliJetContainer *JetContHybridS=0x0; TString strType(type); if (jetShapeType==AliAnalysisTaskSubJetFraction::kTrue) { JetContTrue = task->AddJetContainer(njetsTrue,strType,R); if(JetContTrue) { JetContTrue->SetRhoName(nrhoBase); JetContTrue->ConnectParticleContainer(trackContTrue); JetContTrue->ConnectClusterContainer(clusterCont); JetContTrue->SetPercAreaCut(0.6); JetContTrue->SetJetRadius(R); JetContTrue->SetJetAcceptanceType(AliJetContainer::kTPCfid); JetContTrue->SetPythiaInfoName("PythiaInfo"); } } if (jetShapeType==AliAnalysisTaskSubJetFraction::kGenOnTheFly) { JetContTrue = task->AddJetContainer(njetsTrue,strType,R); if(JetContTrue) { JetContTrue->SetRhoName(nrhoBase); JetContTrue->ConnectParticleContainer(trackContTrue); JetContTrue->ConnectClusterContainer(clusterCont); JetContTrue->SetJetRadius(R); JetContTrue->SetJetAcceptanceType(AliJetContainer::kTPCfid); JetContTrue->SetPercAreaCut(0.6); } } if (jetShapeType==AliAnalysisTaskSubJetFraction::kTrueDet){ JetContDet = task->AddJetContainer(njetsDet,strType,R); //detector level MC if(JetContDet) { JetContDet->SetRhoName(nrhoBase); JetContDet->ConnectParticleContainer(trackContDet); JetContDet->ConnectClusterContainer(clusterCont); JetContDet->SetPercAreaCut(0.6); JetContDet->SetJetRadius(R); JetContDet->SetJetAcceptanceType(AliJetContainer::kTPCfid); JetContDet->SetPythiaInfoName("PythiaInfo"); } JetContTrue = task->AddJetContainer(njetsTrue,strType,R); //Particle Level MC if(JetContTrue) { JetContTrue->SetRhoName(nrhoBase); JetContTrue->ConnectParticleContainer(trackContTrue); JetContTrue->SetPercAreaCut(0.6); JetContTrue->SetJetRadius(R); JetContTrue->SetJetAcceptanceType(AliJetContainer::kTPCfid); JetContTrue->SetPythiaInfoName("PythiaInfo"); } } if (jetShapeType==AliAnalysisTaskSubJetFraction::kData || jetShapeType==AliAnalysisTaskSubJetFraction::kSim){ JetContData = task->AddJetContainer(njetsData,strType,R); //Data if(JetContData) { JetContData->SetRhoName(nrhoBase); JetContData->ConnectParticleContainer(trackContData); JetContData->ConnectClusterContainer(clusterCont); JetContData->SetPercAreaCut(0.6); JetContData->SetJetRadius(R); JetContData->SetJetAcceptanceType(AliJetContainer::kTPCfid); if(jetShapeSub==AliAnalysisTaskSubJetFraction::kConstSub) JetContData->SetAreaEmcCut(-2); } } if (jetShapeType==AliAnalysisTaskSubJetFraction::kDetEmbPart){ JetContHybridS = task->AddJetContainer(njetsHybridS,strType,R); //Subtracted Hybrid (Pb+Pyhthia Det Level) if(JetContHybridS) { JetContHybridS->SetRhoName(nrhoBase); JetContHybridS->ConnectParticleContainer(trackContHybridS); JetContHybridS->ConnectClusterContainer(clusterCont); JetContHybridS->SetPercAreaCut(0.6); JetContHybridS->SetJetRadius(R); JetContHybridS->SetJetAcceptanceType(AliJetContainer::kTPCfid); JetContHybridS->SetPythiaInfoName("PythiaInfo"); if(jetShapeSub==AliAnalysisTaskSubJetFraction::kConstSub) JetContHybridS->SetAreaEmcCut(-2); //?????????? } if(jetShapeSub==AliAnalysisTaskSubJetFraction::kConstSub){ //?????????????????????????? JetContHybridUs=task->AddJetContainer(njetsHybridUs,strType,R); //Unsubtracted Hybrid if(JetContHybridUs) { JetContHybridUs->SetRhoName(nrhoBase); JetContHybridUs->ConnectParticleContainer(trackContHybridUs); JetContHybridUs->SetPercAreaCut(0.6); JetContHybridUs->SetJetRadius(R); JetContHybridUs->SetJetAcceptanceType(AliJetContainer::kTPCfid); JetContHybridUs->SetPythiaInfoName("PythiaInfo"); } } JetContDet = task->AddJetContainer(njetsDet,strType,R); //Pythia Detector Level if(JetContDet) { JetContDet->SetRhoName(nrhoBase); JetContDet->ConnectParticleContainer(trackContDet); JetContDet->SetPercAreaCut(0.6); JetContDet->SetJetRadius(R); JetContDet->SetJetAcceptanceType(AliJetContainer::kTPCfid); JetContDet->SetPythiaInfoName("PythiaInfo"); } JetContTrue = task->AddJetContainer(njetsTrue,strType,R); //Pyhthia Particle Level if(JetContTrue) { JetContTrue->SetRhoName(nrhoBase); JetContTrue->ConnectParticleContainer(trackContTrue); JetContTrue->SetPercAreaCut(0.6); JetContTrue->SetJetRadius(R); JetContTrue->SetJetAcceptanceType(AliJetContainer::kTPCfid); JetContTrue->SetPythiaInfoName("PythiaInfo"); } } task->SetCaloTriggerPatchInfoName(kEmcalTriggers.Data()); task->SetCentralityEstimator(CentEst); task->SelectCollisionCandidates(pSel); task->SetUseAliAnaUtils(kFALSE); mgr->AddTask(task); //Connnect input mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() ); //Connect output TString contName1(wagonName); if (jetShapeType == AliAnalysisTaskSubJetFraction::kTrue) contName1 += "_True"; if (jetShapeType == AliAnalysisTaskSubJetFraction::kTrueDet) contName1 += "_TrueDet"; if (jetShapeType == AliAnalysisTaskSubJetFraction::kData) contName1 += "_Data"; if (jetShapeType == AliAnalysisTaskSubJetFraction::kSim) contName1 += "_Sim"; if (jetShapeType == AliAnalysisTaskSubJetFraction::kDetEmbPart) contName1 += "_DetEmbPart"; if (jetShapeType == AliAnalysisTaskSubJetFraction::kGenOnTheFly) contName1 += "_GenOnTheFly"; if (jetShapeSub == AliAnalysisTaskSubJetFraction::kNoSub) contName1 += "_NoSub"; if (jetShapeSub == AliAnalysisTaskSubJetFraction::kConstSub) contName1 += "_ConstSub"; if (jetShapeSub == AliAnalysisTaskSubJetFraction::kDerivSub && derivSubtrOrder == 0) contName1 += "_DerivSubSecondOrder"; if (jetShapeSub == AliAnalysisTaskSubJetFraction::kDerivSub && derivSubtrOrder == 1) contName1 += "_DerivSubFirstOrder"; if (jetSelection == AliAnalysisTaskSubJetFraction::kInclusive) contName1 += "_Incl"; if (jetSelection == AliAnalysisTaskSubJetFraction::kRecoil) { TString recoilTriggerString = Form("_Recoil_%.0f_%0.f", minpTHTrigger, maxpTHTrigger); contName1 += recoilTriggerString; } TString SubJetRadiusString = Form("_SubJetRadius_%f", SubJetRadius); contName1 += SubJetRadiusString; TString SubJetMinPtString = Form("_SubJetMinPt_%f", SubJetMinPt); contName1 += SubJetMinPtString; TString outputfile = Form("%s",AliAnalysisManager::GetCommonFileName()); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName1.Data(), TTree::Class(),AliAnalysisManager::kOutputContainer,outputfile); mgr->ConnectOutput(task,1,coutput1); return task; } <commit_msg>Taking an argumant out of AddTask<commit_after>AliAnalysisTaskSubJetFraction* AddTaskAliAnalysisTaskSubJetFraction(const char * njetsData, //data jets const char * njetsTrue, //Pyhthia Particle Level const char * njetsDet, const char * njetsHybridUs, const char * njetsHybridS, const Double_t R, const char * nrhoBase, const char * ntracksData, const char * ntracksTrue, const char * ntracksDet, const char * ntracksHybridUs, const char * ntracksHybridS, const char * nclusters, const char *type, const char *CentEst, Double_t fSharedFractionPtMin, Int_t SubJetAlgorithm, Float_t SubJetRadius, Float_t SubJetMinPt, Int_t pSel, TString trigClass = "", TString kEmcalTriggers = "", TString tag = "", AliAnalysisTaskSubJetFraction::JetShapeType jetShapeType, AliAnalysisTaskSubJetFraction::JetShapeSub jetShapeSub, AliAnalysisTaskSubJetFraction::JetSelectionType jetSelection, Float_t minpTHTrigger =0., Float_t maxpTHTrigger =0., AliAnalysisTaskSubJetFraction::DerivSubtrOrder derivSubtrOrder = 0 ) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskAliAnalysisTaskSubJetFraction","No analysis manager found."); return 0; } Bool_t ismc=kFALSE; ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE; // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AliAnalysisTaskSubJetFraction", "This task requires an input event handler"); return NULL; } if (jetShapeType==AliAnalysisTaskSubJetFraction::kData || jetShapeType==AliAnalysisTaskSubJetFraction::kSim) TString wagonName = Form("AliAnalysisTaskSubJetFraction_%s_TC%s%s",njetsData,trigClass.Data(),tag.Data()); if (jetShapeType==AliAnalysisTaskSubJetFraction::kTrue || jetShapeType==AliAnalysisTaskSubJetFraction::kTrueDet || jetShapeType==AliAnalysisTaskSubJetFraction::kGenOnTheFly) TString wagonName = Form("AliAnalysisTaskSubJetFraction_%s_TC%s%s",njetsTrue,trigClass.Data(),tag.Data()); if (jetShapeType==AliAnalysisTaskSubJetFraction::kDetEmbPart) TString wagonName = Form("AliAnalysisTaskSubJetFraction_%s_TC%s%s",njetsHybridS,trigClass.Data(),tag.Data()); //Configure jet tagger task AliAnalysisTaskSubJetFraction *task = new AliAnalysisTaskSubJetFraction(wagonName.Data()); // task->SetNCentBins(4); task->SetJetShapeType(jetShapeType); task->SetJetShapeSub(jetShapeSub); task->SetJetSelection(jetSelection); task->SetSubJetAlgorithm(SubJetAlgorithm); task->SetSubJetRadius(SubJetRadius); task->SetSubJetMinPt(SubJetMinPt); task->SetJetRadius(R); task->SetSharedFractionPtMin(fSharedFractionPtMin); task->SetDerivativeSubtractionOrder(derivSubtrOrder); if (jetSelection == AliAnalysisTaskSubJetFraction::kRecoil) task->SetPtTriggerSelections(minpTHTrigger, maxpTHTrigger); // TString thename(njetsBase); //if(thename.Contains("Sub")) task->SetIsConstSub(kTRUE); //task->SetVzRange(-10.,10.); AliParticleContainer *trackContData=0x0; AliParticleContainer *trackContDet=0x0; if (jetShapeSub == AliAnalysisTaskSubJetFraction::kConstSub){ trackContData = task->AddParticleContainer(ntracksData); trackContDet = task->AddParticleContainer(ntracksDet); } else{ trackContData = task->AddTrackContainer(ntracksData); trackContDet = task->AddTrackContainer(ntracksDet); } AliParticleContainer *trackContTrue = task->AddMCParticleContainer(ntracksTrue); AliParticleContainer *trackContHybridUs = task->AddParticleContainer(ntracksHybridUs); AliParticleContainer *trackContHybridS = task->AddParticleContainer(ntracksHybridS); AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters); AliJetContainer *JetContData=0x0; AliJetContainer *JetContTrue=0x0; AliJetContainer *JetContDet=0x0; AliJetContainer *JetContHybridUs=0x0; AliJetContainer *JetContHybridS=0x0; TString strType(type); if (jetShapeType==AliAnalysisTaskSubJetFraction::kTrue) { JetContTrue = task->AddJetContainer(njetsTrue,strType,R); if(JetContTrue) { JetContTrue->SetRhoName(nrhoBase); JetContTrue->ConnectParticleContainer(trackContTrue); JetContTrue->ConnectClusterContainer(clusterCont); JetContTrue->SetPercAreaCut(0.6); JetContTrue->SetJetRadius(R); JetContTrue->SetJetAcceptanceType(AliJetContainer::kTPCfid); JetContTrue->SetPythiaInfoName("PythiaInfo"); } } if (jetShapeType==AliAnalysisTaskSubJetFraction::kGenOnTheFly) { JetContTrue = task->AddJetContainer(njetsTrue,strType,R); if(JetContTrue) { JetContTrue->SetRhoName(nrhoBase); JetContTrue->ConnectParticleContainer(trackContTrue); JetContTrue->ConnectClusterContainer(clusterCont); JetContTrue->SetJetRadius(R); JetContTrue->SetJetAcceptanceType(AliJetContainer::kTPCfid); JetContTrue->SetPercAreaCut(0.6); } } if (jetShapeType==AliAnalysisTaskSubJetFraction::kTrueDet){ JetContDet = task->AddJetContainer(njetsDet,strType,R); //detector level MC if(JetContDet) { JetContDet->SetRhoName(nrhoBase); JetContDet->ConnectParticleContainer(trackContDet); JetContDet->ConnectClusterContainer(clusterCont); JetContDet->SetPercAreaCut(0.6); JetContDet->SetJetRadius(R); JetContDet->SetJetAcceptanceType(AliJetContainer::kTPCfid); JetContDet->SetPythiaInfoName("PythiaInfo"); } JetContTrue = task->AddJetContainer(njetsTrue,strType,R); //Particle Level MC if(JetContTrue) { JetContTrue->SetRhoName(nrhoBase); JetContTrue->ConnectParticleContainer(trackContTrue); JetContTrue->SetPercAreaCut(0.6); JetContTrue->SetJetRadius(R); JetContTrue->SetJetAcceptanceType(AliJetContainer::kTPCfid); JetContTrue->SetPythiaInfoName("PythiaInfo"); } } if (jetShapeType==AliAnalysisTaskSubJetFraction::kData || jetShapeType==AliAnalysisTaskSubJetFraction::kSim){ JetContData = task->AddJetContainer(njetsData,strType,R); //Data if(JetContData) { JetContData->SetRhoName(nrhoBase); JetContData->ConnectParticleContainer(trackContData); JetContData->ConnectClusterContainer(clusterCont); JetContData->SetPercAreaCut(0.6); JetContData->SetJetRadius(R); JetContData->SetJetAcceptanceType(AliJetContainer::kTPCfid); if(jetShapeSub==AliAnalysisTaskSubJetFraction::kConstSub) JetContData->SetAreaEmcCut(-2); } } if (jetShapeType==AliAnalysisTaskSubJetFraction::kDetEmbPart){ JetContHybridS = task->AddJetContainer(njetsHybridS,strType,R); //Subtracted Hybrid (Pb+Pyhthia Det Level) if(JetContHybridS) { JetContHybridS->SetRhoName(nrhoBase); JetContHybridS->ConnectParticleContainer(trackContHybridS); JetContHybridS->ConnectClusterContainer(clusterCont); JetContHybridS->SetPercAreaCut(0.6); JetContHybridS->SetJetRadius(R); JetContHybridS->SetJetAcceptanceType(AliJetContainer::kTPCfid); JetContHybridS->SetPythiaInfoName("PythiaInfo"); if(jetShapeSub==AliAnalysisTaskSubJetFraction::kConstSub) JetContHybridS->SetAreaEmcCut(-2); //?????????? } if(jetShapeSub==AliAnalysisTaskSubJetFraction::kConstSub){ //?????????????????????????? JetContHybridUs=task->AddJetContainer(njetsHybridUs,strType,R); //Unsubtracted Hybrid if(JetContHybridUs) { JetContHybridUs->SetRhoName(nrhoBase); JetContHybridUs->ConnectParticleContainer(trackContHybridUs); JetContHybridUs->SetPercAreaCut(0.6); JetContHybridUs->SetJetRadius(R); JetContHybridUs->SetJetAcceptanceType(AliJetContainer::kTPCfid); JetContHybridUs->SetPythiaInfoName("PythiaInfo"); } } JetContDet = task->AddJetContainer(njetsDet,strType,R); //Pythia Detector Level if(JetContDet) { JetContDet->SetRhoName(nrhoBase); JetContDet->ConnectParticleContainer(trackContDet); JetContDet->SetPercAreaCut(0.6); JetContDet->SetJetRadius(R); JetContDet->SetJetAcceptanceType(AliJetContainer::kTPCfid); JetContDet->SetPythiaInfoName("PythiaInfo"); } JetContTrue = task->AddJetContainer(njetsTrue,strType,R); //Pyhthia Particle Level if(JetContTrue) { JetContTrue->SetRhoName(nrhoBase); JetContTrue->ConnectParticleContainer(trackContTrue); JetContTrue->SetPercAreaCut(0.6); JetContTrue->SetJetRadius(R); JetContTrue->SetJetAcceptanceType(AliJetContainer::kTPCfid); JetContTrue->SetPythiaInfoName("PythiaInfo"); } } task->SetCaloTriggerPatchInfoName(kEmcalTriggers.Data()); task->SetCentralityEstimator(CentEst); task->SelectCollisionCandidates(pSel); task->SetUseAliAnaUtils(kFALSE); mgr->AddTask(task); //Connnect input mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() ); //Connect output TString contName1(wagonName); if (jetShapeType == AliAnalysisTaskSubJetFraction::kTrue) contName1 += "_True"; if (jetShapeType == AliAnalysisTaskSubJetFraction::kTrueDet) contName1 += "_TrueDet"; if (jetShapeType == AliAnalysisTaskSubJetFraction::kData) contName1 += "_Data"; if (jetShapeType == AliAnalysisTaskSubJetFraction::kSim) contName1 += "_Sim"; if (jetShapeType == AliAnalysisTaskSubJetFraction::kDetEmbPart) contName1 += "_DetEmbPart"; if (jetShapeType == AliAnalysisTaskSubJetFraction::kGenOnTheFly) contName1 += "_GenOnTheFly"; if (jetShapeSub == AliAnalysisTaskSubJetFraction::kNoSub) contName1 += "_NoSub"; if (jetShapeSub == AliAnalysisTaskSubJetFraction::kConstSub) contName1 += "_ConstSub"; if (jetShapeSub == AliAnalysisTaskSubJetFraction::kDerivSub && derivSubtrOrder == 0) contName1 += "_DerivSubSecondOrder"; if (jetShapeSub == AliAnalysisTaskSubJetFraction::kDerivSub && derivSubtrOrder == 1) contName1 += "_DerivSubFirstOrder"; if (jetSelection == AliAnalysisTaskSubJetFraction::kInclusive) contName1 += "_Incl"; if (jetSelection == AliAnalysisTaskSubJetFraction::kRecoil) { TString recoilTriggerString = Form("_Recoil_%.0f_%0.f", minpTHTrigger, maxpTHTrigger); contName1 += recoilTriggerString; } TString SubJetRadiusString = Form("_SubJetRadius_%f", SubJetRadius); contName1 += SubJetRadiusString; TString SubJetMinPtString = Form("_SubJetMinPt_%f", SubJetMinPt); contName1 += SubJetMinPtString; TString outputfile = Form("%s",AliAnalysisManager::GetCommonFileName()); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName1.Data(), TTree::Class(),AliAnalysisManager::kOutputContainer,outputfile); mgr->ConnectOutput(task,1,coutput1); return task; } <|endoftext|>
<commit_before>// PUMI Example // // Compile with: Add GenerateMFEMMesh.cpp in the CMakeLists.txt // // Sample runs: ./GenerateMFEMMesh -m ../data/pumi/serial/sphere.smb // -p ../data/pumi/geom/sphere.x_t -o 1 // // Description: The purpose of this example is to generate MFEM meshes for // complex geometry. The inputs are a Parasolid model, "*.xmt_txt" // and a SCOREC mesh "*.smb". Switch "-o" can be used to increase the // geometric order up to order 6 and consequently write the mesh // in that order. #include "mfem.hpp" #include <fstream> #include <iostream> #include "../mesh/mesh_pumi.hpp" #include "pumi_config.h" #ifdef MFEM_USE_SIMMETRIX #include <SimUtil.h> #include <gmi_sim.h> #endif #include <apfMDS.h> #include <gmi_null.h> #include <PCU.h> #include <apfConvert.h> #include <gmi_mesh.h> #include <crv.h> using namespace std; using namespace mfem; int main(int argc, char *argv[]) { //initilize mpi int num_proc, myId; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &num_proc); MPI_Comm_rank(MPI_COMM_WORLD, &myId); // 1. Parse command-line options. const char *mesh_file = "../data/pumi/serial/sphere.smb"; #ifdef MFEM_USE_SIMMETRIX const char *model_file = "../data/pumi/geom/sphere.x_t"; #else const char *model_file = "../data/pumi/geom/sphere.dmg"; #endif int order = 1; bool visualization = 1; OptionsParser args(argc, argv); args.AddOption(&mesh_file, "-m", "--mesh", "Mesh file to use."); args.AddOption(&order, "-o", "--order", "Finite element order (polynomial degree)."); args.AddOption(&visualization, "-vis", "--visualization", "-no-vis", "--no-visualization", "Enable or disable GLVis visualization."); args.AddOption(&model_file, "-p", "--parasolid", "Parasolid model to use."); args.Parse(); if (!args.Good()) { args.PrintUsage(cout); return 1; } args.PrintOptions(cout); //Read the SCOREC Mesh PCU_Comm_Init(); #ifdef MFEM_USE_SIMMETRIX Sim_readLicenseFile(0); gmi_sim_start(); gmi_register_sim(); #endif gmi_register_mesh(); apf::Mesh2* pumi_mesh; pumi_mesh = apf::loadMdsMesh(model_file, mesh_file); //If it is higher order change shape if (order > 1){ crv::BezierCurver bc(pumi_mesh, order, 2); bc.run(); } pumi_mesh->verify(); // 2. Create the MFEM mesh object from the PUMI mesh. We can handle triangular // and tetrahedral meshes. Other inputs are the same as MFEM default // constructor. Mesh *mesh = new PumiMesh(pumi_mesh, 1, 0); //Write mesh in MFEM fromat ofstream fout("MFEMformat.mesh"); //ofstream fout("MFEMformat.vtku"); fout.precision(8); mesh->Print(fout); //mesh->PrintVTK(fout); delete mesh; pumi_mesh->destroyNative(); apf::destroyMesh(pumi_mesh); PCU_Comm_Free(); #ifdef MFEM_USE_SIMMETRIX gmi_sim_stop(); Sim_unregisterAllKeys(); #endif MPI_Finalize(); return 0; } <commit_msg>Make changes required after review<commit_after><|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief SEEDA03 (RX64M) ใƒกใ‚คใƒณ @copyright Copyright 2017 Kunihito Hiramatsu All Right Reserved. @author ๅนณๆพ้‚ฆไป (hira@rvf-rc45.net) */ //=====================================================================// #include "common/renesas.hpp" #include "common/rspi_io.hpp" #include "common/spi_io.hpp" #include "common/sdc_io.hpp" #include "common/command.hpp" #include "common/fifo.hpp" #include "common/format.hpp" #include "common/input.hpp" #include "common/flash_man.hpp" #include "common/time.h" #include "chip/LTC2348_16.hpp" #include "sample.hpp" #include "chip/EUI_XX.hpp" #include "r_net/http_server.hpp" #include "r_net/ftp_server.hpp" #ifdef DEBUG #define CLIENT_DEBUG #define NETS_DEBUG #define WRITE_FILE_DEBUG #endif namespace seeda { static const int seeda_version_ = 310; static const uint32_t build_id_ = B_ID; typedef utils::command<256> CMD; #ifdef SEEDA typedef device::PORT<device::PORT6, device::bitpos::B7> SW1; typedef device::PORT<device::PORT6, device::bitpos::B6> SW2; #endif // Soft SDC ็”จใ€€SPI ๅฎš็พฉ๏ผˆSPI๏ผ‰ #ifdef SEEDA typedef device::PORT<device::PORTD, device::bitpos::B6> MISO; typedef device::PORT<device::PORTD, device::bitpos::B4> MOSI; typedef device::PORT<device::PORTD, device::bitpos::B5> SPCK; typedef device::spi_io<MISO, MOSI, SPCK> SPI; typedef device::PORT<device::PORTD, device::bitpos::B3> SDC_SELECT; ///< ใ‚ซใƒผใƒ‰้ธๆŠžไฟกๅท typedef device::NULL_PORT SDC_POWER; ///< ใ‚ซใƒผใƒ‰้›ปๆบๅˆถๅพก๏ผˆๅธธใซ้›ปๆบ๏ผฏ๏ผฎ๏ผ‰ typedef device::PORT<device::PORTE, device::bitpos::B6> SDC_DETECT; ///< ใ‚ซใƒผใƒ‰ๆคœๅ‡บ #else // SDC ็”จใ€€SPI ๅฎš็พฉ๏ผˆRSPI๏ผ‰ typedef device::rspi_io<device::RSPI> SPI; typedef device::PORT<device::PORTC, device::bitpos::B4> SDC_SELECT; ///< ใ‚ซใƒผใƒ‰้ธๆŠžไฟกๅท typedef device::NULL_PORT SDC_POWER; ///< ใ‚ซใƒผใƒ‰้›ปๆบๅˆถๅพก๏ผˆๅธธใซ้›ปๆบ๏ผฏ๏ผฎ๏ผ‰ typedef device::PORT<device::PORTB, device::bitpos::B7> SDC_DETECT; ///< ใ‚ซใƒผใƒ‰ๆคœๅ‡บ #endif typedef utils::sdc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> SDC; #ifdef SEEDA // LTC2348-16 A/D ๅˆถๅพกใƒใƒผใƒˆๅฎš็พฉ typedef device::PORT<device::PORT4, device::bitpos::B0> LTC_CSN; // P40(141) typedef device::PORT<device::PORTC, device::bitpos::B6> LTC_CNV; // PC6(61) typedef device::PORT<device::PORTD, device::bitpos::B0> LTC_BUSY; // PD0/IRQ0(126) typedef device::PORT<device::PORT5, device::bitpos::B3> LTC_PD; // P53(53) typedef device::PORT<device::PORT5, device::bitpos::B6> LTC_SDI; // P56(50) typedef device::PORT<device::PORT8, device::bitpos::B6> LTC_SCKO; // P86(41) typedef device::PORT<device::PORT8, device::bitpos::B7> LTC_SCKI; // P87(39) typedef device::PORT<device::PORT2, device::bitpos::B0> LTC_SDO0; // P20(37) typedef device::PORT<device::PORT2, device::bitpos::B1> LTC_SDO2; // P21(36) typedef device::PORT<device::PORT2, device::bitpos::B2> LTC_SDO4; // P22(35) typedef device::PORT<device::PORT2, device::bitpos::B3> LTC_SDO6; // P23(34) typedef struct chip::LTC2348_SDO_t<LTC_SCKO, LTC_SDO0, LTC_SDO2, LTC_SDO4, LTC_SDO6> LTC_SDO; typedef chip::LTC2348_16<LTC_CSN, LTC_CNV, LTC_BUSY, LTC_PD, LTC_SDI, LTC_SCKI, LTC_SDO> EADC; #endif typedef device::flash_io FLASH_IO; typedef utils::flash_man<FLASH_IO> FLASH_MAN; typedef net::http_server<SDC, 16, 8192> HTTP; typedef HTTP::http_format http_format; typedef net::ftp_server<SDC> FTPS; //-----------------------------------------------------------------// /*! @brief SDC_IO ใ‚ฏใƒฉใ‚นใธใฎๅ‚็…ง @return SDC_IO ใ‚ฏใƒฉใ‚น */ //-----------------------------------------------------------------// SDC& at_sdc(); #ifdef SEEDA //-----------------------------------------------------------------// /*! @brief EADC ใ‚ฏใƒฉใ‚นใธใฎๅ‚็…ง @return EADC ใ‚ฏใƒฉใ‚น */ //-----------------------------------------------------------------// EADC& at_eadc(); #endif //-----------------------------------------------------------------// /*! @brief EADC ใ‚ตใƒผใƒใƒผ */ //-----------------------------------------------------------------// void eadc_server(); //-----------------------------------------------------------------// /*! @brief EADC ใ‚ตใƒผใƒใƒผ่จฑๅฏ @param[in] ena ใ€Œfalseใ€ใฎๅ ดๅˆไธ่จฑๅฏ */ //-----------------------------------------------------------------// void enable_eadc_server(bool ena = true); //-----------------------------------------------------------------// /*! @brief ๆ™‚้–“ใฎไฝœๆˆ @param[in] date ๆ—ฅไป˜ @param[in] time ๆ™‚้–“ */ //-----------------------------------------------------------------// size_t make_time(const char* date, const char* time); //-----------------------------------------------------------------// /*! @brief GMT ๆ™‚้–“ใฎ่จญๅฎš @param[in] t GMT ๆ™‚้–“ */ //-----------------------------------------------------------------// void set_time(time_t t); //-----------------------------------------------------------------// /*! @brief ๆ™‚้–“ใฎ่กจ็คบ @param[in] t ๆ™‚้–“ @param[in] dst ๅ‡บๅŠ›ๆ–‡ๅญ—ๅˆ— @param[in] size ๆ–‡ๅญ—ๅˆ—ใฎๅคงใใ• @return ็”Ÿๆˆใ•ใ‚ŒใŸๆ–‡ๅญ—ๅˆ—ใฎ้•ทใ• */ //-----------------------------------------------------------------// int disp_time(time_t t, char* dst = nullptr, uint32_t size = 0); //-----------------------------------------------------------------// /*! @brief ่จญๅฎšใ‚นใ‚คใƒƒใƒใฎ็Šถๆ…‹ใ‚’ๅ–ๅพ— @return ่จญๅฎšใ‚นใ‚คใƒƒใƒใฎ็Šถๆ…‹ */ //-----------------------------------------------------------------// uint8_t get_switch() { #ifdef SEEDA return static_cast<uint8_t>(!SW1::P()) | (static_cast<uint8_t>(!SW2::P()) << 1); #else return 0; // for only develope mode #endif } //-----------------------------------------------------------------// /*! @brief A/D ใ‚ตใƒณใƒ—ใƒซใฎๅ‚็…ง @param[in] ch ใƒใƒฃใƒใƒซ๏ผˆ๏ผ๏ฝž๏ผ—๏ผ‰ @return A/D ใ‚ตใƒณใƒ—ใƒซ */ //-----------------------------------------------------------------// sample_t& at_sample(uint8_t ch); //-----------------------------------------------------------------// /*! @brief A/D ใ‚ตใƒณใƒ—ใƒซใฎๅ–ๅพ— @return A/D ใ‚ตใƒณใƒ—ใƒซ */ //-----------------------------------------------------------------// const sample_data& get_sample_data(); //-----------------------------------------------------------------// /*! @brief ๅ†…่‡“ A/D ๅค‰ๆ›ๅ€คใฎๅ–ๅพ— @param[in] ch ใƒใƒฃใƒใƒซ๏ผˆ๏ผ•ใ€๏ผ–ใ€๏ผ—๏ผ‰ @return A/D ๅค‰ๆ›ๅ€ค */ //-----------------------------------------------------------------// uint16_t get_adc(uint32_t ch); } extern "C" { //-----------------------------------------------------------------// /*! @brief GMT ๆ™‚้–“ใฎๅ–ๅพ— @return GMT ๆ™‚้–“ */ //-----------------------------------------------------------------// time_t get_time(); }; <commit_msg>update version NO<commit_after>#pragma once //=====================================================================// /*! @file @brief SEEDA03 (RX64M) ใƒกใ‚คใƒณ @copyright Copyright 2017 Kunihito Hiramatsu All Right Reserved. @author ๅนณๆพ้‚ฆไป (hira@rvf-rc45.net) */ //=====================================================================// #include "common/renesas.hpp" #include "common/rspi_io.hpp" #include "common/spi_io.hpp" #include "common/sdc_io.hpp" #include "common/command.hpp" #include "common/fifo.hpp" #include "common/format.hpp" #include "common/input.hpp" #include "common/flash_man.hpp" #include "common/time.h" #include "chip/LTC2348_16.hpp" #include "sample.hpp" #include "chip/EUI_XX.hpp" #include "r_net/http_server.hpp" #include "r_net/ftp_server.hpp" #ifdef DEBUG #define CLIENT_DEBUG #define NETS_DEBUG #define WRITE_FILE_DEBUG #endif namespace seeda { static const int seeda_version_ = 322; static const uint32_t build_id_ = B_ID; typedef utils::command<256> CMD; #ifdef SEEDA typedef device::PORT<device::PORT6, device::bitpos::B7> SW1; typedef device::PORT<device::PORT6, device::bitpos::B6> SW2; #endif // Soft SDC ็”จใ€€SPI ๅฎš็พฉ๏ผˆSPI๏ผ‰ #ifdef SEEDA typedef device::PORT<device::PORTD, device::bitpos::B6> MISO; typedef device::PORT<device::PORTD, device::bitpos::B4> MOSI; typedef device::PORT<device::PORTD, device::bitpos::B5> SPCK; typedef device::spi_io<MISO, MOSI, SPCK> SPI; typedef device::PORT<device::PORTD, device::bitpos::B3> SDC_SELECT; ///< ใ‚ซใƒผใƒ‰้ธๆŠžไฟกๅท typedef device::NULL_PORT SDC_POWER; ///< ใ‚ซใƒผใƒ‰้›ปๆบๅˆถๅพก๏ผˆๅธธใซ้›ปๆบ๏ผฏ๏ผฎ๏ผ‰ typedef device::PORT<device::PORTE, device::bitpos::B6> SDC_DETECT; ///< ใ‚ซใƒผใƒ‰ๆคœๅ‡บ #else // SDC ็”จใ€€SPI ๅฎš็พฉ๏ผˆRSPI๏ผ‰ typedef device::rspi_io<device::RSPI> SPI; typedef device::PORT<device::PORTC, device::bitpos::B4> SDC_SELECT; ///< ใ‚ซใƒผใƒ‰้ธๆŠžไฟกๅท typedef device::NULL_PORT SDC_POWER; ///< ใ‚ซใƒผใƒ‰้›ปๆบๅˆถๅพก๏ผˆๅธธใซ้›ปๆบ๏ผฏ๏ผฎ๏ผ‰ typedef device::PORT<device::PORTB, device::bitpos::B7> SDC_DETECT; ///< ใ‚ซใƒผใƒ‰ๆคœๅ‡บ #endif typedef utils::sdc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> SDC; #ifdef SEEDA // LTC2348-16 A/D ๅˆถๅพกใƒใƒผใƒˆๅฎš็พฉ typedef device::PORT<device::PORT4, device::bitpos::B0> LTC_CSN; // P40(141) typedef device::PORT<device::PORTC, device::bitpos::B6> LTC_CNV; // PC6(61) typedef device::PORT<device::PORTD, device::bitpos::B0> LTC_BUSY; // PD0/IRQ0(126) typedef device::PORT<device::PORT5, device::bitpos::B3> LTC_PD; // P53(53) typedef device::PORT<device::PORT5, device::bitpos::B6> LTC_SDI; // P56(50) typedef device::PORT<device::PORT8, device::bitpos::B6> LTC_SCKO; // P86(41) typedef device::PORT<device::PORT8, device::bitpos::B7> LTC_SCKI; // P87(39) typedef device::PORT<device::PORT2, device::bitpos::B0> LTC_SDO0; // P20(37) typedef device::PORT<device::PORT2, device::bitpos::B1> LTC_SDO2; // P21(36) typedef device::PORT<device::PORT2, device::bitpos::B2> LTC_SDO4; // P22(35) typedef device::PORT<device::PORT2, device::bitpos::B3> LTC_SDO6; // P23(34) typedef struct chip::LTC2348_SDO_t<LTC_SCKO, LTC_SDO0, LTC_SDO2, LTC_SDO4, LTC_SDO6> LTC_SDO; typedef chip::LTC2348_16<LTC_CSN, LTC_CNV, LTC_BUSY, LTC_PD, LTC_SDI, LTC_SCKI, LTC_SDO> EADC; #endif typedef device::flash_io FLASH_IO; typedef utils::flash_man<FLASH_IO> FLASH_MAN; typedef net::http_server<SDC, 16, 8192> HTTP; typedef HTTP::http_format http_format; typedef net::ftp_server<SDC> FTPS; //-----------------------------------------------------------------// /*! @brief SDC_IO ใ‚ฏใƒฉใ‚นใธใฎๅ‚็…ง @return SDC_IO ใ‚ฏใƒฉใ‚น */ //-----------------------------------------------------------------// SDC& at_sdc(); #ifdef SEEDA //-----------------------------------------------------------------// /*! @brief EADC ใ‚ฏใƒฉใ‚นใธใฎๅ‚็…ง @return EADC ใ‚ฏใƒฉใ‚น */ //-----------------------------------------------------------------// EADC& at_eadc(); #endif //-----------------------------------------------------------------// /*! @brief EADC ใ‚ตใƒผใƒใƒผ */ //-----------------------------------------------------------------// void eadc_server(); //-----------------------------------------------------------------// /*! @brief EADC ใ‚ตใƒผใƒใƒผ่จฑๅฏ @param[in] ena ใ€Œfalseใ€ใฎๅ ดๅˆไธ่จฑๅฏ */ //-----------------------------------------------------------------// void enable_eadc_server(bool ena = true); //-----------------------------------------------------------------// /*! @brief ๆ™‚้–“ใฎไฝœๆˆ @param[in] date ๆ—ฅไป˜ @param[in] time ๆ™‚้–“ */ //-----------------------------------------------------------------// size_t make_time(const char* date, const char* time); //-----------------------------------------------------------------// /*! @brief GMT ๆ™‚้–“ใฎ่จญๅฎš @param[in] t GMT ๆ™‚้–“ */ //-----------------------------------------------------------------// void set_time(time_t t); //-----------------------------------------------------------------// /*! @brief ๆ™‚้–“ใฎ่กจ็คบ @param[in] t ๆ™‚้–“ @param[in] dst ๅ‡บๅŠ›ๆ–‡ๅญ—ๅˆ— @param[in] size ๆ–‡ๅญ—ๅˆ—ใฎๅคงใใ• @return ็”Ÿๆˆใ•ใ‚ŒใŸๆ–‡ๅญ—ๅˆ—ใฎ้•ทใ• */ //-----------------------------------------------------------------// int disp_time(time_t t, char* dst = nullptr, uint32_t size = 0); //-----------------------------------------------------------------// /*! @brief ่จญๅฎšใ‚นใ‚คใƒƒใƒใฎ็Šถๆ…‹ใ‚’ๅ–ๅพ— @return ่จญๅฎšใ‚นใ‚คใƒƒใƒใฎ็Šถๆ…‹ */ //-----------------------------------------------------------------// uint8_t get_switch() { #ifdef SEEDA return static_cast<uint8_t>(!SW1::P()) | (static_cast<uint8_t>(!SW2::P()) << 1); #else return 0; // for only develope mode #endif } //-----------------------------------------------------------------// /*! @brief A/D ใ‚ตใƒณใƒ—ใƒซใฎๅ‚็…ง @param[in] ch ใƒใƒฃใƒใƒซ๏ผˆ๏ผ๏ฝž๏ผ—๏ผ‰ @return A/D ใ‚ตใƒณใƒ—ใƒซ */ //-----------------------------------------------------------------// sample_t& at_sample(uint8_t ch); //-----------------------------------------------------------------// /*! @brief A/D ใ‚ตใƒณใƒ—ใƒซใฎๅ–ๅพ— @return A/D ใ‚ตใƒณใƒ—ใƒซ */ //-----------------------------------------------------------------// const sample_data& get_sample_data(); //-----------------------------------------------------------------// /*! @brief ๅ†…่‡“ A/D ๅค‰ๆ›ๅ€คใฎๅ–ๅพ— @param[in] ch ใƒใƒฃใƒใƒซ๏ผˆ๏ผ•ใ€๏ผ–ใ€๏ผ—๏ผ‰ @return A/D ๅค‰ๆ›ๅ€ค */ //-----------------------------------------------------------------// uint16_t get_adc(uint32_t ch); } extern "C" { //-----------------------------------------------------------------// /*! @brief GMT ๆ™‚้–“ใฎๅ–ๅพ— @return GMT ๆ™‚้–“ */ //-----------------------------------------------------------------// time_t get_time(); }; <|endoftext|>
<commit_before>/** * @file * @brief Implementation of Geant4 deposition module * @remarks Based on code from Mathieu Benoit * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors. * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md". * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an * Intergovernmental Organization or submit itself to any jurisdiction. */ #include "DepositionGeant4Module.hpp" #include <limits> #include <string> #include <utility> #include <G4EmParameters.hh> #include <G4HadronicProcessStore.hh> #include <G4LogicalVolume.hh> #include <G4PhysListFactory.hh> #include <G4RunManager.hh> #include <G4StepLimiterPhysics.hh> #include <G4UImanager.hh> #include <G4UserLimits.hh> #include "core/config/exceptions.h" #include "core/geometry/GeometryManager.hpp" #include "core/module/exceptions.h" #include "core/utils/log.h" #include "objects/DepositedCharge.hpp" #include "tools/ROOT.h" #include "tools/geant4.h" #include "GeneratorActionG4.hpp" #include "SensitiveDetectorActionG4.hpp" #define G4_NUM_SEEDS 10 using namespace allpix; /** * Includes the particle source point to the geometry using \ref GeometryManager::addPoint. */ DepositionGeant4Module::DepositionGeant4Module(Configuration config, Messenger* messenger, GeometryManager* geo_manager) : Module(config), config_(std::move(config)), messenger_(messenger), geo_manager_(geo_manager), last_event_num_(1), run_manager_g4_(nullptr) { // Create user limits for maximum step length in the sensor user_limits_ = std::make_unique<G4UserLimits>(config_.get<double>("max_step_length", Units::get(1.0, "um"))); // Set default physics list config_.setDefault("physics_list", "FTFP_BERT_LIV"); // Add the particle source position to the geometry geo_manager_->addPoint(config_.get<ROOT::Math::XYZPoint>("beam_position")); } /** * Module depends on \ref GeometryBuilderGeant4Module loaded first, because it owns the pointer to the Geant4 run manager. */ void DepositionGeant4Module::init() { // Load the G4 run manager (which is owned by the geometry builder) run_manager_g4_ = G4RunManager::GetRunManager(); if(run_manager_g4_ == nullptr) { throw ModuleError("Cannot deposit charges using Geant4 without a Geant4 geometry builder"); } // Suppress all output from G4 SUPPRESS_STREAM(G4cout); // Get UI manager for sending commands G4UImanager* ui_g4 = G4UImanager::GetUIpointer(); // Apply optional PAI model if(config_.get<bool>("enable_pai", false)) { LOG(TRACE) << "Enabling PAI model on all detectors"; G4EmParameters::Instance(); for(auto& detector : geo_manager_->getDetectors()) { // Get logical volume auto logical_volume = detector->getExternalObject<G4LogicalVolume>("sensor_log"); if(logical_volume == nullptr) { throw ModuleError("Detector " + detector->getName() + " has no sensitive device (broken Geant4 geometry)"); } // Create region G4Region* region = new G4Region(detector->getName() + "_sensor_region"); region->AddRootLogicalVolume(logical_volume.get()); auto pai_model = config_.get<std::string>("pai_model", "pai"); auto lcase_model = pai_model; std::transform(lcase_model.begin(), lcase_model.end(), lcase_model.begin(), ::tolower); if(lcase_model == "pai") { pai_model = "PAI"; } else if(lcase_model == "paiphoton") { pai_model = "PAIphoton"; } else { throw InvalidValueError(config_, "pai_model", "model has to be either 'pai' or 'paiphoton'"); } ui_g4->ApplyCommand("/process/em/AddPAIRegion all " + region->GetName() + " " + pai_model); } } // Find the physics list G4PhysListFactory physListFactory; G4VModularPhysicsList* physicsList = physListFactory.GetReferencePhysList(config_.get<std::string>("physics_list")); if(physicsList == nullptr) { std::string message = "specified physics list does not exists"; std::vector<G4String> base_lists = physListFactory.AvailablePhysLists(); message += " (available base lists are "; for(auto& base_list : base_lists) { message += base_list; message += ", "; } message = message.substr(0, message.size() - 2); message += " with optional suffixes for electromagnetic lists "; std::vector<G4String> em_lists = physListFactory.AvailablePhysListsEM(); for(auto& em_list : em_lists) { if(em_list.empty()) { continue; } message += em_list; message += ", "; } message = message.substr(0, message.size() - 2); message += ")"; throw InvalidValueError(config_, "physics_list", message); } else { LOG(INFO) << "Using G4 physics list \"" << config_.get<std::string>("physics_list") << "\""; } // Register a step limiter (uses the user limits defined earlier) physicsList->RegisterPhysics(new G4StepLimiterPhysics()); // Initialize the physics list LOG(TRACE) << "Initializing physics processes"; run_manager_g4_->SetUserInitialization(physicsList); run_manager_g4_->InitializePhysics(); // Initialize the full run manager to ensure correct state flags run_manager_g4_->Initialize(); // Build particle generator LOG(TRACE) << "Constructing particle source"; auto generator = new GeneratorActionG4(config_); run_manager_g4_->SetUserAction(generator); // Get the creation energy for charge (default is silicon electron hole pair energy) auto charge_creation_energy = config_.get<double>("charge_creation_energy", Units::get(3.64, "eV")); // Loop through all detectors and set the sensitive detector action that handles the particle passage bool useful_deposition = false; for(auto& detector : geo_manager_->getDetectors()) { // Do not add sensitive detector for detectors that have no listeners for the deposited charges // FIXME Probably the MCParticle has to be checked as well if(!messenger_->hasReceiver(this, std::make_shared<DepositedChargeMessage>(std::vector<DepositedCharge>(), detector))) { LOG(INFO) << "Not depositing charges in " << detector->getName() << " because there is no listener for its output"; continue; } useful_deposition = true; // Get model of the sensitive device auto sensitive_detector_action = new SensitiveDetectorActionG4(this, detector, messenger_, charge_creation_energy); auto logical_volume = detector->getExternalObject<G4LogicalVolume>("sensor_log"); if(logical_volume == nullptr) { throw ModuleError("Detector " + detector->getName() + " has no sensitive device (broken Geant4 geometry)"); } // Apply the user limits to this element logical_volume->SetUserLimits(user_limits_.get()); // Add the sensitive detector action logical_volume->SetSensitiveDetector(sensitive_detector_action); sensors_.push_back(sensitive_detector_action); } if(!useful_deposition) { LOG(ERROR) << "Not a single listener for deposited charges, module is useless!"; } // Disable verbose messages from processes ui_g4->ApplyCommand("/process/verbose 0"); ui_g4->ApplyCommand("/process/em/verbose 0"); ui_g4->ApplyCommand("/process/eLoss/verbose 0"); G4HadronicProcessStore::Instance()->SetVerbose(0); // Set the random seed for Geant4 generation // NOTE Assumes this is the only Geant4 module using random numbers std::string seed_command = "/random/setSeeds "; for(int i = 0; i < G4_NUM_SEEDS; ++i) { seed_command += std::to_string(static_cast<uint32_t>(getRandomSeed() % INT_MAX)); if(i != G4_NUM_SEEDS - 1) { seed_command += " "; } } ui_g4->ApplyCommand(seed_command); // Release the output stream RELEASE_STREAM(G4cout); } void DepositionGeant4Module::run(unsigned int event_num) { // Suppress output stream if not in debugging mode IFLOG(DEBUG); else { SUPPRESS_STREAM(G4cout); } // Start a single event from the beam LOG(TRACE) << "Enabling beam"; run_manager_g4_->BeamOn(static_cast<int>(config_.get<unsigned int>("number_of_particles", 1))); last_event_num_ = event_num; // Release the stream (if it was suspended) RELEASE_STREAM(G4cout); // Dispatch the necessary messages for(auto& sensor : sensors_) { sensor->dispatchMessages(); } } void DepositionGeant4Module::finalize() { size_t total_charges = 0; for(auto& sensor : sensors_) { total_charges += sensor->getTotalDepositedCharge(); } // Print summary or warns if module did not output any charges if(!sensors_.empty() && total_charges > 0 && last_event_num_ > 0) { size_t average_charge = total_charges / sensors_.size() / last_event_num_; LOG(INFO) << "Deposited total of " << total_charges << " charges in " << sensors_.size() << " sensor(s) (average of " << average_charge << " per sensor for every event)"; } else { LOG(WARNING) << "No charges deposited"; } } <commit_msg>Implement production cut in DepositionGeant4<commit_after>/** * @file * @brief Implementation of Geant4 deposition module * @remarks Based on code from Mathieu Benoit * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors. * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md". * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an * Intergovernmental Organization or submit itself to any jurisdiction. */ #include "DepositionGeant4Module.hpp" #include <limits> #include <string> #include <utility> #include <G4EmParameters.hh> #include <G4HadronicProcessStore.hh> #include <G4LogicalVolume.hh> #include <G4PhysListFactory.hh> #include <G4RunManager.hh> #include <G4StepLimiterPhysics.hh> #include <G4UImanager.hh> #include <G4UserLimits.hh> #include "core/config/exceptions.h" #include "core/geometry/GeometryManager.hpp" #include "core/module/exceptions.h" #include "core/utils/log.h" #include "objects/DepositedCharge.hpp" #include "tools/ROOT.h" #include "tools/geant4.h" #include "GeneratorActionG4.hpp" #include "SensitiveDetectorActionG4.hpp" #define G4_NUM_SEEDS 10 using namespace allpix; /** * Includes the particle source point to the geometry using \ref GeometryManager::addPoint. */ DepositionGeant4Module::DepositionGeant4Module(Configuration config, Messenger* messenger, GeometryManager* geo_manager) : Module(config), config_(std::move(config)), messenger_(messenger), geo_manager_(geo_manager), last_event_num_(1), run_manager_g4_(nullptr) { // Create user limits for maximum step length in the sensor user_limits_ = std::make_unique<G4UserLimits>(config_.get<double>("max_step_length", Units::get(1.0, "um"))); // Set default physics list config_.setDefault("physics_list", "FTFP_BERT_LIV"); // Add the particle source position to the geometry geo_manager_->addPoint(config_.get<ROOT::Math::XYZPoint>("beam_position")); } /** * Module depends on \ref GeometryBuilderGeant4Module loaded first, because it owns the pointer to the Geant4 run manager. */ void DepositionGeant4Module::init() { // Load the G4 run manager (which is owned by the geometry builder) run_manager_g4_ = G4RunManager::GetRunManager(); if(run_manager_g4_ == nullptr) { throw ModuleError("Cannot deposit charges using Geant4 without a Geant4 geometry builder"); } // Suppress all output from G4 SUPPRESS_STREAM(G4cout); // Get UI manager for sending commands G4UImanager* ui_g4 = G4UImanager::GetUIpointer(); // Apply optional PAI model if(config_.get<bool>("enable_pai", false)) { LOG(TRACE) << "Enabling PAI model on all detectors"; G4EmParameters::Instance(); for(auto& detector : geo_manager_->getDetectors()) { // Get logical volume auto logical_volume = detector->getExternalObject<G4LogicalVolume>("sensor_log"); if(logical_volume == nullptr) { throw ModuleError("Detector " + detector->getName() + " has no sensitive device (broken Geant4 geometry)"); } // Create region G4Region* region = new G4Region(detector->getName() + "_sensor_region"); region->AddRootLogicalVolume(logical_volume.get()); auto pai_model = config_.get<std::string>("pai_model", "pai"); auto lcase_model = pai_model; std::transform(lcase_model.begin(), lcase_model.end(), lcase_model.begin(), ::tolower); if(lcase_model == "pai") { pai_model = "PAI"; } else if(lcase_model == "paiphoton") { pai_model = "PAIphoton"; } else { throw InvalidValueError(config_, "pai_model", "model has to be either 'pai' or 'paiphoton'"); } ui_g4->ApplyCommand("/process/em/AddPAIRegion all " + region->GetName() + " " + pai_model); } } // Find the physics list G4PhysListFactory physListFactory; G4VModularPhysicsList* physicsList = physListFactory.GetReferencePhysList(config_.get<std::string>("physics_list")); if(physicsList == nullptr) { std::string message = "specified physics list does not exists"; std::vector<G4String> base_lists = physListFactory.AvailablePhysLists(); message += " (available base lists are "; for(auto& base_list : base_lists) { message += base_list; message += ", "; } message = message.substr(0, message.size() - 2); message += " with optional suffixes for electromagnetic lists "; std::vector<G4String> em_lists = physListFactory.AvailablePhysListsEM(); for(auto& em_list : em_lists) { if(em_list.empty()) { continue; } message += em_list; message += ", "; } message = message.substr(0, message.size() - 2); message += ")"; throw InvalidValueError(config_, "physics_list", message); } else { LOG(INFO) << "Using G4 physics list \"" << config_.get<std::string>("physics_list") << "\""; } // Register a step limiter (uses the user limits defined earlier) physicsList->RegisterPhysics(new G4StepLimiterPhysics()); //Define the production cut as one fifth of the minimum size (thickness, pitch) among the detectors double min_size = std::numeric_limits<double>::max(); for(auto& detector : geo_manager_->getDetectors()) { auto model = detector->getModel(); min_size = std::min(std::min(std::min(min_size, model->getPixelSize().x()), model->getPixelSize().y()), model->getSensorSize().z()); } auto production_cut = std::to_string(min_size/5); ui_g4->ApplyCommand("/run/setCut " + production_cut); // Initialize the physics list LOG(TRACE) << "Initializing physics processes"; run_manager_g4_->SetUserInitialization(physicsList); run_manager_g4_->InitializePhysics(); // Initialize the full run manager to ensure correct state flags run_manager_g4_->Initialize(); // Build particle generator LOG(TRACE) << "Constructing particle source"; auto generator = new GeneratorActionG4(config_); run_manager_g4_->SetUserAction(generator); // Get the creation energy for charge (default is silicon electron hole pair energy) auto charge_creation_energy = config_.get<double>("charge_creation_energy", Units::get(3.64, "eV")); // Loop through all detectors and set the sensitive detector action that handles the particle passage bool useful_deposition = false; for(auto& detector : geo_manager_->getDetectors()) { // Do not add sensitive detector for detectors that have no listeners for the deposited charges // FIXME Probably the MCParticle has to be checked as well if(!messenger_->hasReceiver(this, std::make_shared<DepositedChargeMessage>(std::vector<DepositedCharge>(), detector))) { LOG(INFO) << "Not depositing charges in " << detector->getName() << " because there is no listener for its output"; continue; } useful_deposition = true; // Get model of the sensitive device auto sensitive_detector_action = new SensitiveDetectorActionG4(this, detector, messenger_, charge_creation_energy); auto logical_volume = detector->getExternalObject<G4LogicalVolume>("sensor_log"); if(logical_volume == nullptr) { throw ModuleError("Detector " + detector->getName() + " has no sensitive device (broken Geant4 geometry)"); } // Apply the user limits to this element logical_volume->SetUserLimits(user_limits_.get()); // Add the sensitive detector action logical_volume->SetSensitiveDetector(sensitive_detector_action); sensors_.push_back(sensitive_detector_action); } if(!useful_deposition) { LOG(ERROR) << "Not a single listener for deposited charges, module is useless!"; } // Disable verbose messages from processes ui_g4->ApplyCommand("/process/verbose 0"); ui_g4->ApplyCommand("/process/em/verbose 0"); ui_g4->ApplyCommand("/process/eLoss/verbose 0"); G4HadronicProcessStore::Instance()->SetVerbose(0); // Set the random seed for Geant4 generation // NOTE Assumes this is the only Geant4 module using random numbers std::string seed_command = "/random/setSeeds "; for(int i = 0; i < G4_NUM_SEEDS; ++i) { seed_command += std::to_string(static_cast<uint32_t>(getRandomSeed() % INT_MAX)); if(i != G4_NUM_SEEDS - 1) { seed_command += " "; } } ui_g4->ApplyCommand(seed_command); // Release the output stream RELEASE_STREAM(G4cout); } void DepositionGeant4Module::run(unsigned int event_num) { // Suppress output stream if not in debugging mode IFLOG(DEBUG); else { SUPPRESS_STREAM(G4cout); } // Start a single event from the beam LOG(TRACE) << "Enabling beam"; run_manager_g4_->BeamOn(static_cast<int>(config_.get<unsigned int>("number_of_particles", 1))); last_event_num_ = event_num; // Release the stream (if it was suspended) RELEASE_STREAM(G4cout); // Dispatch the necessary messages for(auto& sensor : sensors_) { sensor->dispatchMessages(); } } void DepositionGeant4Module::finalize() { size_t total_charges = 0; for(auto& sensor : sensors_) { total_charges += sensor->getTotalDepositedCharge(); } // Print summary or warns if module did not output any charges if(!sensors_.empty() && total_charges > 0 && last_event_num_ > 0) { size_t average_charge = total_charges / sensors_.size() / last_event_num_; LOG(INFO) << "Deposited total of " << total_charges << " charges in " << sensors_.size() << " sensor(s) (average of " << average_charge << " per sensor for every event)"; } else { LOG(WARNING) << "No charges deposited"; } } <|endoftext|>
<commit_before>// Copyright (c) 2012, Steinwurf ApS // 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 Steinwurf ApS 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 Steinwurf ApS 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 "file_input_stream.hpp" #include "error.hpp" #include <fstream> #include <cassert> namespace sak { file_input_stream::file_input_stream() : m_filesize(0) { } file_input_stream::file_input_stream(const std::string& filename) : m_filesize(0) { open(filename); } void file_input_stream::open(const std::string& filename) { assert(!m_file.is_open()); boost::system::error_code ec; open(filename, ec); // If an error throw error::throw_error(ec); } void file_input_stream::open(const std::string& filename, boost::system::error_code& ec) { assert(!m_file.is_open()); m_file.open(filename.c_str(), std::ios::in | std::ios::binary); if (!m_file.is_open()) { ec = error::make_error_code(error::failed_open_file); return; } m_file.seekg(0, std::ios::end); assert(m_file); m_filesize = read_position(); m_file.seekg(0, std::ios::beg); assert(m_file); } void file_input_stream::seek(uint32_t pos) { assert(m_file.is_open()); m_file.seekg(pos, std::ios::beg); assert(m_file); // if(m_file.fail()) // { // ec = error::make_error_code(error::failed_open_file); // return; // } } uint32_t file_input_stream::read_position() { assert(m_file.is_open()); std::cout << "EOF " << m_file.eof() << std::endl; std::streamoff pos = m_file.tellg(); std::cout << "tellg = " << (int32_t) pos << std::endl; assert(pos >= 0); return static_cast<uint32_t>(pos); } void file_input_stream::read(uint8_t* buffer, uint32_t bytes) { assert(m_file.is_open()); std::cout << "file_input_stream::read " << bytes << std::endl; m_file.read(reinterpret_cast<char*>(buffer), bytes); assert(bytes == static_cast<uint32_t>(m_file.gcount())); } uint32_t file_input_stream::bytes_available() { assert(m_file.is_open()); std::cout << "file_input_stream::bytes_available " << std::endl; uint32_t pos = read_position(); assert(pos <= m_filesize); return m_filesize - pos; } uint32_t file_input_stream::size() { assert(m_file.is_open()); return m_filesize; } } <commit_msg>Check for EOF when checking read_position()<commit_after>// Copyright (c) 2012, Steinwurf ApS // 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 Steinwurf ApS 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 Steinwurf ApS 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 "file_input_stream.hpp" #include "error.hpp" #include <fstream> #include <cassert> namespace sak { file_input_stream::file_input_stream() : m_filesize(0) { } file_input_stream::file_input_stream(const std::string& filename) : m_filesize(0) { open(filename); } void file_input_stream::open(const std::string& filename) { assert(!m_file.is_open()); boost::system::error_code ec; open(filename, ec); // If an error throw error::throw_error(ec); } void file_input_stream::open(const std::string& filename, boost::system::error_code& ec) { assert(!m_file.is_open()); m_file.open(filename.c_str(), std::ios::in | std::ios::binary); if (!m_file.is_open()) { ec = error::make_error_code(error::failed_open_file); return; } m_file.seekg(0, std::ios::end); assert(m_file); // We cannot use the read_position function here due to a // problem on the iOS platform described in the read_position // function. auto pos = m_file.tellg(); assert(pos >= 0); m_filesize = (uint32_t) pos; m_file.seekg(0, std::ios::beg); assert(m_file); } void file_input_stream::seek(uint32_t pos) { assert(m_file.is_open()); m_file.seekg(pos, std::ios::beg); assert(m_file); // if(m_file.fail()) // { // ec = error::make_error_code(error::failed_open_file); // return; // } } uint32_t file_input_stream::read_position() { assert(m_file.is_open()); // Work around for problem on iOS where tellg returned -1 when // reading the last byte. However the EOF flag was correctly // set. So here we check for EOF if true we set the // read_position = m_file_size if(m_file.eof()) { return m_file_size; } else { std::streamoff pos = m_file.tellg(); std::cout << "tellg = " << (int32_t) pos << std::endl; assert(pos >= 0); return static_cast<uint32_t>(pos); } } void file_input_stream::read(uint8_t* buffer, uint32_t bytes) { assert(m_file.is_open()); std::cout << "file_input_stream::read " << bytes << std::endl; m_file.read(reinterpret_cast<char*>(buffer), bytes); assert(bytes == static_cast<uint32_t>(m_file.gcount())); } uint32_t file_input_stream::bytes_available() { assert(m_file.is_open()); std::cout << "file_input_stream::bytes_available " << std::endl; uint32_t pos = read_position(); assert(pos <= m_filesize); return m_filesize - pos; } uint32_t file_input_stream::size() { assert(m_file.is_open()); return m_filesize; } } <|endoftext|>
<commit_before>#include "simulator.hpp" #include <float.h> void SMSimulator::init(itpp::bvec _inputBits) { inputBits = _inputBits; Nt = itpp::length(inputBits); ofs << "SNR[dB],BER" << std::endl; m = log2(nC * nTx); if (Nt % m != 0) { inputBits = itpp::concat(inputBits, itpp::zeros_b(Nt % m)); Nt = itpp::length(inputBits); // Refresh } Nu = Nt; /* !!!Warning!!! : nAntenna must be modified */ nAntenna = itpp::length(itpp::dec2bin(nTx)) - 1; nSymbols = nC; nSymbin = itpp::length(itpp::dec2bin(nSymbols)) - 1; modulator.set_M(nSymbols); Nctx = Nu; Nvec = Nctx / m; Nbitspvec = m; std::cout << m << " " << Nu << " " << Nctx << " " << Nvec << " " << Nbitspvec << std::endl; return; } void SMxSimulator::init(itpp::bvec _inputBits) { inputBits = _inputBits; Nt = itpp::length(inputBits); ofs << "SNR[dB],BER" << std::endl; m = log2(nC) * nTx; if (Nt % m != 0) { inputBits = itpp::concat(inputBits, itpp::zeros_b(Nt % m)); Nt = itpp::length(inputBits); // Refresh } Nu = Nt; modulator.set_M(nTx, nC); Nctx = Nu; Nvec = Nctx / m; Nbitspvec = m; std::cout << m << " " << Nu << " " << Nctx << " " << Nvec << " " << Nbitspvec << std::endl; return; } itpp::cvec SMSimulator::select_antenna(itpp::bvec bits) { itpp::cvec s = itpp::zeros_c(nTx); // ใ‚ขใƒณใƒ†ใƒŠๆ•ฐ int Nbits = itpp::length(bits); int selected_antenna = itpp::bin2dec(bits(0, nAntenna - 1)); std::complex<double> symbol = modulator.get_symbols()(itpp::bin2dec(bits(nAntenna, Nbits - 1))); if (nAntenna == 0) { s(0) = symbol; } else { s(selected_antenna) = symbol; } return s; } itpp::vec SMSimulator::demodulate_bits(itpp::cvec Y, itpp::cmat H, itpp::cvec S, itpp::Array<itpp::cvec> samples) { int i = 0, argmax_P; const double coef = pow(itpp::pi, -nRx); itpp::vec P(nTx * nSymbols); itpp::vec j_q_pair(2); for (int j = 0; j < nTx; j++) { for (int q = 0; q < nSymbols; q++) { if (nTx == 1) { P(i++) = -itpp::norm(Y - H * samples(nSymbols * j + q)); } else { P(i++) = coef * exp(-itpp::norm(Y - H * samples(nSymbols * j + q), "fro")); } } } argmax_P = itpp::max_index(P); j_q_pair(0) = argmax_P / nSymbols; j_q_pair(1) = argmax_P % nSymbols; return j_q_pair; } itpp::Array<itpp::cvec> SMSimulator::get_samples() { itpp::cvec symbols = modulator.get_symbols(); itpp::Array<itpp::cvec> samples(nSymbols * nTx); itpp::cvec tmp; for (int i = 0; i < nTx; i++) { for (int j = 0; j < nSymbols; j++) { tmp = itpp::zeros_c(nTx); tmp(i) = symbols(j); samples(nSymbols * i + j) = tmp; } } return samples; } itpp::bvec SMSimulator::simulate(int TotalNumSimulate) { std::cout.setf(std::ios::fixed, std::ios::floatfield); std::cout.setf(std::ios::showpoint); //std::cout.setf(std::ios::scientific, std::ios::floatfield); std::cout.precision(10); for (int nsnr = 0; nsnr <= TotalNumSimulate; nsnr++) { itpp::cvec Y; itpp::cmat H; itpp::cvec S; itpp::cvec e; itpp::Array<itpp::cvec> Samples = SMSimulator::get_samples(); const double sigma2 = itpp::inv_dB(-nsnr); itpp::BERC bercu; itpp::bvec bitstmp; itpp::vec j_q_pair; itpp::bvec transmittmp; itpp::bvec receivetmp; itpp::bvec transmitted(Nctx); itpp::bvec received(Nctx); for (int k = 0; k < Nvec; k++) { H = itpp::randn_c(nRx, nTx); bitstmp = inputBits(k * Nbitspvec, (k + 1) * Nbitspvec - 1); S = SMSimulator::select_antenna(bitstmp); e = sqrt(sigma2) * itpp::randn_c(nRx); Y = H * S + e; j_q_pair = SMSimulator::demodulate_bits(Y, H, S, Samples); transmittmp = bitstmp; receivetmp = itpp::concat(itpp::dec2bin(nAntenna, static_cast<int>(j_q_pair(0))), itpp::dec2bin(nSymbin, static_cast<int>(j_q_pair(1))) ); transmitted.set_subvector(k * Nbitspvec, transmittmp); received.set_subvector(k * Nbitspvec, receivetmp); } bercu.count(transmitted(0, Nu - 1), received(0, Nu - 1)); std::cout << "-----------------------------------------------------" << std::endl; std::cout << "Eb/N0: " << nsnr << " dB. Simulated " << Nctx << " bits." << std::endl; //std::cout << " Uncoded BER: " << error_rate << " (ML)" << std::endl; std::cout << " Uncoded BER: " << bercu.get_errorrate() << " (ML)" << std::endl; ofs << std::dec << nsnr << "," << std::scientific << bercu.get_errorrate() << std::endl; // Debug return received; } return itpp::bvec(1); } itpp::bvec SMxSimulator::simulate(int TotalNumSimulate) { const int Nmethods = 1; std::cout.setf(std::ios::fixed, std::ios::floatfield); std::cout.setf(std::ios::showpoint); std::cout.precision(10); for (int nsnr = 0; nsnr <= TotalNumSimulate; nsnr++) { itpp::Array<itpp::cvec> Y(Nvec); itpp::Array<itpp::cmat> H(Nvec + 1); itpp::cvec e; const double sigma2 = itpp::inv_dB(-nsnr); itpp::BERC bercu; itpp::bvec bitstmp; itpp::bvec received(Nu); for (int k = 0; k < Nvec; k++) { H(k) = itpp::randn_c(nRx, nTx); bitstmp = inputBits(k * Nbitspvec, (k + 1) * Nbitspvec - 1); e = sqrt(sigma2) * itpp::randn_c(nRx); //std::cout << length(bitstmp) << " " << sum(modulator.get_k()) << "\n"; itpp::cvec x = modulator.modulate_bits(bitstmp); Y(k) = H(k) * x + e; //std::cout << modulator(Y(k)) << std::endl; /* received.set_subvector(k * Nbitspvec, modulator.get_symbols()(0)(itpp::bin2dec(Y(k))) ); */ } // -- demodulate -- itpp::Array<itpp::QLLRvec> LLRin(Nmethods); for (int i = 0; i < Nmethods; i++) { LLRin(i) = itpp::zeros_i(Nctx); } itpp::QLLRvec llr_apr = itpp::zeros_i(Nbitspvec); itpp::QLLRvec llr_apost = itpp::zeros_i(Nbitspvec); for (int k = 0; k < Nvec; k++) { // ML demodulation modulator.demodulate_soft_bits(Y(k), H(k), sigma2, llr_apr, llr_apost); LLRin(0).set_subvector(k * Nbitspvec, llr_apost); } // -- decode and count errors -- for (int i = 0; i < Nmethods; i++) { bercu.count(inputBits(0, Nu - 1), LLRin(0)(0, Nu - 1) < 0); } // -- received bits -- for (int i = 0; i < Nu; i++) { received(i) = LLRin(0)(i) < 0; } //bercu.count(transmitted(0, Nu - 1), received(0, Nu - 1)); std::cout << "-----------------------------------------------------" << std::endl; std::cout << "Eb/N0: " << nsnr << " dB. Simulated " << Nctx << " bits." << std::endl; //std::cout << " Uncoded BER: " << error_rate << " (ML)" << std::endl; std::cout << " Uncoded BER: " << bercu.get_errorrate() << " (ML)" << std::endl; ofs << std::dec << nsnr << "," << std::scientific << bercu.get_errorrate() << std::endl; // Debug return received; } return itpp::bvec(1); } <commit_msg>Modify some indents<commit_after>#include "simulator.hpp" #include <float.h> void SMSimulator::init(itpp::bvec _inputBits) { inputBits = _inputBits; Nt = itpp::length(inputBits); ofs << "SNR[dB],BER" << std::endl; m = log2(nC * nTx); if (Nt % m != 0) { inputBits = itpp::concat(inputBits, itpp::zeros_b(Nt % m)); Nt = itpp::length(inputBits); // Refresh } Nu = Nt; nAntenna = itpp::length(itpp::dec2bin(nTx)) - 1; nSymbols = nC; nSymbin = itpp::length(itpp::dec2bin(nSymbols)) - 1; modulator.set_M(nSymbols); Nctx = Nu; Nvec = Nctx / m; Nbitspvec = m; std::cout << m << " " << Nu << " " << Nctx << " " << Nvec << " " << Nbitspvec << std::endl; return; } void SMxSimulator::init(itpp::bvec _inputBits) { inputBits = _inputBits; Nt = itpp::length(inputBits); ofs << "SNR[dB],BER" << std::endl; m = log2(nC) * nTx; if (Nt % m != 0) { inputBits = itpp::concat(inputBits, itpp::zeros_b(Nt % m)); Nt = itpp::length(inputBits); // Refresh } Nu = Nt; modulator.set_M(nTx, m); Nctx = Nu; Nvec = Nctx / m; Nbitspvec = m; std::cout << m << " " << Nu << " " << Nctx << " " << Nvec << " " << Nbitspvec << std::endl; return; } itpp::cvec SMSimulator::select_antenna(itpp::bvec bits) { itpp::cvec s = itpp::zeros_c(nTx); // ใ‚ขใƒณใƒ†ใƒŠๆ•ฐ int Nbits = itpp::length(bits); int selected_antenna = itpp::bin2dec(bits(0, nAntenna - 1)); std::complex<double> symbol = modulator.get_symbols()(itpp::bin2dec(bits(nAntenna, Nbits - 1))); if (nAntenna == 0) { s(0) = symbol; } else { s(selected_antenna) = symbol; } return s; } itpp::vec SMSimulator::demodulate_bits(itpp::cvec Y, itpp::cmat H, itpp::cvec S, itpp::Array<itpp::cvec> samples) { int i = 0, argmax_P; const double coef = pow(itpp::pi, -nRx); itpp::vec P(nTx * nSymbols); itpp::vec j_q_pair(2); for (int j = 0; j < nTx; j++) { for (int q = 0; q < nSymbols; q++) { if (nTx == 1) { P(i++) = -itpp::norm(Y - H * samples(nSymbols * j + q)); } else { P(i++) = coef * exp(-itpp::norm(Y - H * samples(nSymbols * j + q), "fro")); } } } argmax_P = itpp::max_index(P); j_q_pair(0) = argmax_P / nSymbols; j_q_pair(1) = argmax_P % nSymbols; return j_q_pair; } itpp::Array<itpp::cvec> SMSimulator::get_samples() { itpp::cvec symbols = modulator.get_symbols(); itpp::Array<itpp::cvec> samples(nSymbols * nTx); itpp::cvec tmp; for (int i = 0; i < nTx; i++) { for (int j = 0; j < nSymbols; j++) { tmp = itpp::zeros_c(nTx); tmp(i) = symbols(j); samples(nSymbols * i + j) = tmp; } } return samples; } itpp::bvec SMSimulator::simulate(int nsnr) { itpp::cvec Y; itpp::cmat H; itpp::cvec S; itpp::cvec e; itpp::Array<itpp::cvec> Samples = SMSimulator::get_samples(); const double sigma2 = itpp::inv_dB(-nsnr); itpp::BERC bercu; itpp::bvec bitstmp; itpp::vec j_q_pair; itpp::bvec transmittmp; itpp::bvec receivetmp; itpp::bvec transmitted(Nctx); itpp::bvec received(Nctx); for (int k = 0; k < Nvec; k++) { H = itpp::randn_c(nRx, nTx); bitstmp = inputBits(k * Nbitspvec, (k + 1) * Nbitspvec - 1); S = SMSimulator::select_antenna(bitstmp); e = sqrt(sigma2) * itpp::randn_c(nRx); Y = H * S + e; j_q_pair = SMSimulator::demodulate_bits(Y, H, S, Samples); transmittmp = bitstmp; receivetmp = itpp::concat(itpp::dec2bin(nAntenna, static_cast<int>(j_q_pair(0))), itpp::dec2bin(nSymbin, static_cast<int>(j_q_pair(1))) ); transmitted.set_subvector(k * Nbitspvec, transmittmp); received.set_subvector(k * Nbitspvec, receivetmp); } bercu.count(transmitted(0, Nu - 1), received(0, Nu - 1)); std::cout << "-----------------------------------------------------" << std::endl; std::cout << "Eb/N0: " << nsnr << " dB. Simulated " << Nctx << " bits." << std::endl; std::cout << "BER: " << bercu.get_errorrate() << " (ML)" << std::endl; ofs << std::dec << nsnr << "," << std::scientific << bercu.get_errorrate() << std::endl; return received; } itpp::bvec SMxSimulator::simulate(int nsnr) { const int Nmethods = 1; const double sigma2 = itpp::inv_dB(-nsnr); itpp::Array<itpp::cvec> Y(Nvec); itpp::Array<itpp::cmat> H(Nvec + 1); itpp::cvec e; itpp::BERC bercu; itpp::bvec bitstmp; itpp::bvec received(Nu); for (int k = 0; k < Nvec; k++) { H(k) = itpp::randn_c(nRx, nTx); bitstmp = inputBits(k * Nbitspvec, (k + 1) * Nbitspvec - 1); e = sqrt(sigma2) * itpp::randn_c(nRx); itpp::cvec x = modulator.modulate_bits(bitstmp); Y(k) = H(k) * x + e; } // -- demodulate -- itpp::Array<itpp::QLLRvec> LLRin(Nmethods); for (int i = 0; i < Nmethods; i++) { LLRin(i) = itpp::zeros_i(Nctx); } itpp::QLLRvec llr_apr = itpp::zeros_i(Nbitspvec); itpp::QLLRvec llr_apost = itpp::zeros_i(Nbitspvec); for (int k = 0; k < Nvec; k++) { // ML demodulation modulator.demodulate_soft_bits(Y(k), H(k), sigma2, llr_apr, llr_apost); LLRin(0).set_subvector(k * Nbitspvec, llr_apost); } // -- decode and count errors -- for (int i = 0; i < Nmethods; i++) { bercu.count(inputBits(0, Nu - 1), LLRin(0)(0, Nu - 1) < 0); } // -- received bits -- for (int i = 0; i < Nu; i++) { received(i) = LLRin(0)(i) < 0; } std::cout << "-----------------------------------------------------" << std::endl; std::cout << "Eb/N0: " << nsnr << " dB. Simulated " << Nctx << " bits." << std::endl; std::cout << "BER: " << bercu.get_errorrate() << " (ML)" << std::endl; ofs << std::dec << nsnr << "," << std::scientific << bercu.get_errorrate() << std::endl; return received; } <|endoftext|>
<commit_before>//$Id: ResultsPostProcessor.h 3456 2013-06-26 02:11:13Z Jamshid $ /* * The Software is made available solely for use according to the License Agreement. Any reproduction * or redistribution of the Software not in accordance with the License Agreement is expressly prohibited * by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the * maximum extent possible. * * THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT * AS WARRANTED IN THE LICENSE AGREEMENT, SRCH2 INC. HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH * REGARD TO THE SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL SRCH2 INC. BE LIABLE FOR ANY * SPECIAL, 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 ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF SOFTWARE. * Copyright ยฉ 2010 SRCH2 Inc. All rights reserved */ #include "FacetedSearchFilterInternal.h" #include <vector> #include <map> #include <string> #include <algorithm> #include "util/Assert.h" #include "instantsearch/TypedValue.h" #include "util/DateAndTimeHandler.h" using namespace std; namespace srch2 { namespace instantsearch { float FacetResultsContainer::initAggregation(FacetAggregationType aggregationType){ switch (aggregationType) { case FacetAggregationTypeCount: return 0; default: ASSERT(false); return 0; } } float FacetResultsContainer::doAggregation(float bucketValue, FacetAggregationType aggregationType){ switch (aggregationType) { case FacetAggregationTypeCount: return bucketValue + 1; default: ASSERT(false); return 0; } } void CategoricalFacetResultsContainer::initialize(FacetHelper * facetHelper , FacetAggregationType aggregationType){ // No need to do anything in this function. } void CategoricalFacetResultsContainer::addResultToBucket(const unsigned bucketId, const std::string & bucketName, FacetAggregationType aggregationType){ std::map<unsigned, std::pair<std::string, float> >::iterator bucketIter = bucketsInfo.find(bucketId); if( bucketIter == bucketsInfo.end()){ // A new bucket std::pair<std::string, float> newBucket = std::make_pair(bucketName , initAggregation(aggregationType)); newBucket.second = doAggregation(newBucket.second , aggregationType); bucketsInfo[bucketId] = newBucket; }else{ bucketIter->second.second = doAggregation(bucketIter->second.second , aggregationType); } } void CategoricalFacetResultsContainer::getNamesAndValues(std::vector<std::pair< std::string, float > > & results){ for(std::map<unsigned, std::pair<std::string, float> >::iterator bucketPtr = bucketsInfo.begin() ; bucketPtr != bucketsInfo.end() ; ++bucketPtr){ results.push_back(std::make_pair(bucketPtr->second.first , bucketPtr->second.second)); } } /* * Since we want to include all intervals of a range facet (even if they don't have any records in them) * we have to first initialize all intervals to a value (e.g. count of 0). To do this we use facetHelper to give us * a list of IDs which it will generate later with their name. For example: * <0,"-inf">,<1,"10">,<2,"20">,<3,"30"> */ void RangeFacetResultsContainer::initialize(FacetHelper * facetHelper , FacetAggregationType aggregationType){ std::vector<std::pair<unsigned, std::string> > idsAndNames; facetHelper->generateListOfIdsAndNames(&idsAndNames); int index = 0; for(std::vector<std::pair<unsigned, std::string> >::iterator idAndName = idsAndNames.begin(); idAndName != idsAndNames.end() ; ++idAndName){ ASSERT(index == idAndName->first); // bucket Id must be the index of buckets in this vector bucketsInfo.push_back(std::make_pair(idAndName->second , initAggregation(aggregationType) )); // index++; } } void RangeFacetResultsContainer::addResultToBucket(const unsigned bucketId, const std::string & bucketName, FacetAggregationType aggregationType){ bucketsInfo.at(bucketId).second = doAggregation(bucketsInfo.at(bucketId).second , aggregationType); } void RangeFacetResultsContainer::getNamesAndValues(std::vector<std::pair< std::string, float > > & results){ results.insert(results.begin(), bucketsInfo.begin() , bucketsInfo.end()); } std::pair<unsigned , std::string> CategoricalFacetHelper::generateIDAndName(const TypedValue & attributeValue){ std::string attributeValueLowerCase = attributeValue.toString(); std::transform(attributeValueLowerCase.begin(), attributeValueLowerCase.end(), attributeValueLowerCase.begin(), ::tolower); if(categoryValueToBucketIdMap.find(attributeValueLowerCase) == categoryValueToBucketIdMap.end()){ categoryValueToBucketIdMap[attributeValueLowerCase] = categoryValueToBucketIdMap.size(); } return std::make_pair(categoryValueToBucketIdMap[attributeValueLowerCase] , attributeValueLowerCase); } void CategoricalFacetHelper::generateListOfIdsAndNames(std::vector<std::pair<unsigned, std::string> > * idsAndNames){ // This function should not be called. ASSERT(false); } void CategoricalFacetHelper::initialize(const std::string * facetInfoForInitialization, const Schema * schema){ // No need to do anything here } /* * This function finds the interval in which attributeValue is placed. ID and name will be returned. since all the names are returned once * in generateListOfIdsAndNames, all names are returned as "" to save copying string values. */ std::pair<unsigned , std::string> RangeFacetHelper::generateIDAndName(const TypedValue & attributeValue){ if(attributeValue >= end){ return std::make_pair(numberOfBuckets-1 , ""); } unsigned bucketId = attributeValue.findIndexOfContainingInterval(start, end, gap); if(bucketId == -1){ // Something has gone wrong and Score class has been unable to calculate the index. ASSERT(false); return std::make_pair(0 , "");; } if(bucketId >= numberOfBuckets){ bucketId = numberOfBuckets - 1; } return std::make_pair(bucketId , ""); } /* * Example : * If we have two attributes : price,model (facet type : range, categorical) * and start,end and gap for price are 1,100 and 10. Then this function * produces an empty vector for model (because it's categorical) and a vector with the following * values for price: * -large_value, 1, 11, 21, 31, 41, ..., 91, 101 */ void RangeFacetHelper::generateListOfIdsAndNames(std::vector<std::pair<unsigned, std::string> > * idsAndNames){ if(generateListOfIdsAndNamesFlag == true || idsAndNames == NULL){ ASSERT(false); return; } TypedValue lowerBoundToAdd = start; std::vector<TypedValue> lowerBounds; // Example : start : 1, gap : 10 , end : 100 // first -large_value is added as the first category // then 1, 11, 21, ...and 91 are added in the loop. // and 101 is added after loop. lowerBounds.push_back(lowerBoundToAdd.minimumValue()); // to collect data smaller than start while (lowerBoundToAdd < end) { lowerBounds.push_back(lowerBoundToAdd); // data of normal categories lowerBoundToAdd = lowerBoundToAdd + gap; } lowerBounds.push_back(end); // to collect data greater than end // now set the number of buckets numberOfBuckets = lowerBounds.size(); // now fill the output for(int lowerBoundsIndex = 0; lowerBoundsIndex < lowerBounds.size() ; lowerBoundsIndex++){ string bucketName = lowerBounds.at(lowerBoundsIndex).toString(); if(attributeType == ATTRIBUTE_TYPE_TIME){ long timeValue = lowerBounds.at(lowerBoundsIndex).getTimeTypedValue(); bucketName = DateAndTimeHandler::convertSecondsFromEpochToDateTimeString(&timeValue); } idsAndNames->push_back(std::make_pair(lowerBoundsIndex , bucketName)); } // And set the flag to make sure this function is called only once. generateListOfIdsAndNamesFlag = false; } /* * Info must contain : * facetInfoForInitialization[0] <= start * facetInfoForInitialization[1] <= end * facetInfoForInitialization[2] <= gap * facetInfoForInitialization[3] <= fieldName */ void RangeFacetHelper::initialize(const std::string * facetInfoForInitialization , const Schema * schema){ std::string startString = facetInfoForInitialization[0]; std::string endString = facetInfoForInitialization[1]; std::string gapString = facetInfoForInitialization[2]; std::string fieldName = facetInfoForInitialization[3]; attributeType = schema->getTypeOfNonSearchableAttribute( schema->getNonSearchableAttributeId(fieldName)); start.setTypedValue(attributeType, startString); end.setTypedValue(attributeType, endString); if(attributeType == ATTRIBUTE_TYPE_TIME){ // For time attributes gap should not be of the same type, it should be // of type TimeDuration. if(start > end){ // start should not be greater than end start = end; gap.setTypedValue(ATTRIBUTE_TYPE_DURATION, "00:00:00"); }else{ gap.setTypedValue(ATTRIBUTE_TYPE_DURATION, gapString); } }else{ if(start > end){ // start should not be greater than end start = end; gap.setTypedValue(attributeType , "0"); }else{ gap.setTypedValue(attributeType, gapString); } } } void FacetedSearchFilterInternal::doFilter(IndexSearcher *indexSearcher, const Query * query, QueryResults * input, QueryResults * output){ IndexSearcherInternal * indexSearcherInternal = dynamic_cast<IndexSearcherInternal *>(indexSearcher); Schema * schema = indexSearcherInternal->getSchema(); ForwardIndex * forwardIndex = indexSearcherInternal->getForwardIndex(); // first prepare internal structures based on the input preFilter(indexSearcher); // also copy all input results to output to save previous filter works output->copyForPostProcessing(input); // translate list of attribute names to list of attribute IDs std::vector<unsigned> attributeIds; for(std::vector<std::string>::iterator facetField = fields.begin(); facetField != fields.end() ; ++facetField){ attributeIds.push_back(schema->getNonSearchableAttributeId(*facetField)); } // move on the results once and do all facet calculations. for (std::vector<QueryResult *>::iterator resultIter = output->impl->sortedFinalResults.begin(); resultIter != output->impl->sortedFinalResults.end(); ++resultIter) { QueryResult * queryResult = *resultIter; // extract all facet related nonsearchable attribute values from this record // by accessing the forward index only once. bool isValid = false; const ForwardList * list = forwardIndex->getForwardList( queryResult->internalRecordId, isValid); ASSERT(isValid); const Byte * nonSearchableAttributesData = list->getNonSearchableAttributeContainerData(); // this vector is parallel to attributeIds vector std::vector<TypedValue> attributeDataValues; VariableLengthAttributeContainer::getBatchOfAttributes(attributeIds, schema,nonSearchableAttributesData, &attributeDataValues); // now iterate on attributes and incrementally update the facet results for(std::vector<std::string>::iterator facetField = fields.begin(); facetField != fields.end() ; ++facetField){ TypedValue & attributeValue = attributeDataValues.at( std::distance(fields.begin() , facetField)); // choose the type of aggregation for this attribute // increments the correct facet by one doProcessOneResult(attributeValue , std::distance(fields.begin() , facetField)); } } // now copy all results to output for(std::vector<std::pair< FacetType , FacetResultsContainer * > >::iterator facetResultsPtr = facetResults.begin(); facetResultsPtr != facetResults.end(); ++facetResultsPtr){ std::vector<std::pair< std::string, float > > results; facetResultsPtr->second->getNamesAndValues(results); output->impl->facetResults[fields.at(std::distance(facetResults.begin() , facetResultsPtr))] = std::make_pair(facetResultsPtr->first , results); } } void FacetedSearchFilterInternal::preFilter(IndexSearcher *indexSearcher){ IndexSearcherInternal * indexSearcherInternal = dynamic_cast<IndexSearcherInternal *>(indexSearcher); Schema * schema = indexSearcherInternal->getSchema(); for(std::vector<std::string>::iterator facetField = fields.begin(); facetField != fields.end() ; ++facetField){ FacetType facetType = facetTypes.at(std::distance(fields.begin() , facetField)); FacetHelper * facetHelper = NULL; FacetResultsContainer * facetResultsContainer = NULL; switch (facetType) { case FacetTypeCategorical: facetHelper = new CategoricalFacetHelper(); facetResultsContainer = new CategoricalFacetResultsContainer(); break; case FacetTypeRange: facetHelper = new RangeFacetHelper(); facetResultsContainer = new RangeFacetResultsContainer(); break; default: ASSERT(false); break; } std::string info[4]; info[0] = rangeStarts.at(std::distance(fields.begin() , facetField)); info[1] = rangeEnds.at(std::distance(fields.begin() , facetField)); info[2] = rangeGaps.at(std::distance(fields.begin() , facetField)); info[3] = *facetField; facetHelper->initialize(info , schema); facetResultsContainer->initialize(facetHelper , FacetAggregationTypeCount ); this->facetResults.push_back(std::make_pair(facetType , facetResultsContainer)); this->facetHelpers.push_back(facetHelper); } } void FacetedSearchFilterInternal::doProcessOneResult(const TypedValue & attributeValue, const unsigned facetFieldIndex){ std::pair<unsigned , std::string> idandName = this->facetHelpers.at(facetFieldIndex)->generateIDAndName(attributeValue); this->facetResults.at(facetFieldIndex).second->addResultToBucket(idandName.first , idandName.second , FacetAggregationTypeCount); } void FacetedSearchFilterInternal::initialize(std::vector<FacetType> & facetTypes, std::vector<std::string> & fields, std::vector<std::string> & rangeStarts, std::vector<std::string> & rangeEnds, std::vector<std::string> & rangeGaps){ this->fields = fields; this->facetTypes = facetTypes; this->rangeStarts = rangeStarts; this->rangeEnds = rangeEnds; this->rangeGaps = rangeGaps; } } } <commit_msg>Code review comments are applied.<commit_after>//$Id: ResultsPostProcessor.h 3456 2013-06-26 02:11:13Z Jamshid $ /* * The Software is made available solely for use according to the License Agreement. Any reproduction * or redistribution of the Software not in accordance with the License Agreement is expressly prohibited * by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the * maximum extent possible. * * THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT * AS WARRANTED IN THE LICENSE AGREEMENT, SRCH2 INC. HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH * REGARD TO THE SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL SRCH2 INC. BE LIABLE FOR ANY * SPECIAL, 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 ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF SOFTWARE. * Copyright ยฉ 2010 SRCH2 Inc. All rights reserved */ #include "FacetedSearchFilterInternal.h" #include <vector> #include <map> #include <string> #include <algorithm> #include "util/Assert.h" #include "instantsearch/TypedValue.h" #include "util/DateAndTimeHandler.h" using namespace std; namespace srch2 { namespace instantsearch { float FacetResultsContainer::initAggregation(FacetAggregationType aggregationType){ switch (aggregationType) { case FacetAggregationTypeCount: return 0; default: ASSERT(false); return 0; } } float FacetResultsContainer::doAggregation(float bucketValue, FacetAggregationType aggregationType){ switch (aggregationType) { case FacetAggregationTypeCount: return bucketValue + 1; default: ASSERT(false); return 0; } } void CategoricalFacetResultsContainer::initialize(FacetHelper * facetHelper , FacetAggregationType aggregationType){ // No need to do anything in this function. } void CategoricalFacetResultsContainer::addResultToBucket(const unsigned bucketId, const std::string & bucketName, FacetAggregationType aggregationType){ std::map<unsigned, std::pair<std::string, float> >::iterator bucketIter = bucketsInfo.find(bucketId); if( bucketIter == bucketsInfo.end()){ // A new bucket std::pair<std::string, float> newBucket = std::make_pair(bucketName , initAggregation(aggregationType)); newBucket.second = doAggregation(newBucket.second , aggregationType); bucketsInfo[bucketId] = newBucket; }else{ bucketIter->second.second = doAggregation(bucketIter->second.second , aggregationType); } } void CategoricalFacetResultsContainer::getNamesAndValues(std::vector<std::pair< std::string, float > > & results){ for(std::map<unsigned, std::pair<std::string, float> >::iterator bucketPtr = bucketsInfo.begin() ; bucketPtr != bucketsInfo.end() ; ++bucketPtr){ results.push_back(std::make_pair(bucketPtr->second.first , bucketPtr->second.second)); } } /* * Since we want to include all intervals of a range facet (even if they don't have any records in them) * we have to first initialize all intervals to a value (e.g. count of 0). To do this we use facetHelper to give us * a list of IDs which it will generate later with their name. For example: * <0,"-inf">,<1,"10">,<2,"20">,<3,"30"> */ void RangeFacetResultsContainer::initialize(FacetHelper * facetHelper , FacetAggregationType aggregationType){ std::vector<std::pair<unsigned, std::string> > idsAndNames; facetHelper->generateListOfIdsAndNames(&idsAndNames); int index = 0; for(std::vector<std::pair<unsigned, std::string> >::iterator idAndName = idsAndNames.begin(); idAndName != idsAndNames.end() ; ++idAndName){ ASSERT(index == idAndName->first); // bucket Id must be the index of buckets in this vector bucketsInfo.push_back(std::make_pair(idAndName->second , initAggregation(aggregationType) )); // index++; } } void RangeFacetResultsContainer::addResultToBucket(const unsigned bucketId, const std::string & bucketName, FacetAggregationType aggregationType){ bucketsInfo.at(bucketId).second = doAggregation(bucketsInfo.at(bucketId).second , aggregationType); } void RangeFacetResultsContainer::getNamesAndValues(std::vector<std::pair< std::string, float > > & results){ results.insert(results.begin(), bucketsInfo.begin() , bucketsInfo.end()); } std::pair<unsigned , std::string> CategoricalFacetHelper::generateIDAndName(const TypedValue & attributeValue){ std::string attributeValueLowerCase = attributeValue.toString(); std::transform(attributeValueLowerCase.begin(), attributeValueLowerCase.end(), attributeValueLowerCase.begin(), ::tolower); if(categoryValueToBucketIdMap.find(attributeValueLowerCase) == categoryValueToBucketIdMap.end()){ categoryValueToBucketIdMap[attributeValueLowerCase] = categoryValueToBucketIdMap.size(); } return std::make_pair(categoryValueToBucketIdMap[attributeValueLowerCase] , attributeValueLowerCase); } void CategoricalFacetHelper::generateListOfIdsAndNames(std::vector<std::pair<unsigned, std::string> > * idsAndNames){ // This function should not be called. ASSERT(false); } void CategoricalFacetHelper::initialize(const std::string * facetInfoForInitialization, const Schema * schema){ // No need to do anything here } /* * This function finds the interval in which attributeValue is placed. ID and name will be returned. since all the names are returned once * in generateListOfIdsAndNames, all names are returned as "" to save copying string values. */ std::pair<unsigned , std::string> RangeFacetHelper::generateIDAndName(const TypedValue & attributeValue){ if(attributeValue >= end){ return std::make_pair(numberOfBuckets-1 , ""); } unsigned bucketId = attributeValue.findIndexOfContainingInterval(start, end, gap); if(bucketId == -1){ // Something has gone wrong and Score class has been unable to calculate the index. ASSERT(false); return std::make_pair(0 , "");; } if(bucketId >= numberOfBuckets){ bucketId = numberOfBuckets - 1; } return std::make_pair(bucketId , ""); } /* * Example : * If we have two attributes : price,model (facet type : range, categorical) * and start,end and gap for price are 1,100 and 10. Then this function * produces an empty vector for model (because it's categorical) and a vector with the following * values for price: * -large_value, 1, 11, 21, 31, 41, ..., 91, 101 */ void RangeFacetHelper::generateListOfIdsAndNames(std::vector<std::pair<unsigned, std::string> > * idsAndNames){ if(generateListOfIdsAndNamesFlag == true || idsAndNames == NULL){ ASSERT(false); return; } TypedValue lowerBoundToAdd = start; std::vector<TypedValue> lowerBounds; // Example : start : 1, gap : 10 , end : 100 // first -large_value is added as the first category // then 1, 11, 21, ...and 91 are added in the loop. // and 101 is added after loop. lowerBounds.push_back(lowerBoundToAdd.minimumValue()); // to collect data smaller than start while (lowerBoundToAdd < end) { lowerBounds.push_back(lowerBoundToAdd); // data of normal categories lowerBoundToAdd = lowerBoundToAdd + gap; } lowerBounds.push_back(end); // to collect data greater than end // now set the number of buckets numberOfBuckets = lowerBounds.size(); // now fill the output for(int lowerBoundsIndex = 0; lowerBoundsIndex < lowerBounds.size() ; lowerBoundsIndex++){ string bucketName = lowerBounds.at(lowerBoundsIndex).toString(); /* * If the type of this facet attribute is time, we should translate the number of * seconds from Jan 1st 1970 (aka "epoch") to a human readable representation of time. * For example, if this value is 1381271294, the name of this bucket is 10/8/2013 3:28:14. */ if(attributeType == ATTRIBUTE_TYPE_TIME){ long timeValue = lowerBounds.at(lowerBoundsIndex).getTimeTypedValue(); bucketName = DateAndTimeHandler::convertSecondsFromEpochToDateTimeString(&timeValue); } idsAndNames->push_back(std::make_pair(lowerBoundsIndex , bucketName)); } // And set the flag to make sure this function is called only once. generateListOfIdsAndNamesFlag = false; } /* * Info must contain : * facetInfoForInitialization[0] <= start * facetInfoForInitialization[1] <= end * facetInfoForInitialization[2] <= gap * facetInfoForInitialization[3] <= fieldName */ void RangeFacetHelper::initialize(const std::string * facetInfoForInitialization , const Schema * schema){ std::string startString = facetInfoForInitialization[0]; std::string endString = facetInfoForInitialization[1]; std::string gapString = facetInfoForInitialization[2]; std::string fieldName = facetInfoForInitialization[3]; attributeType = schema->getTypeOfNonSearchableAttribute( schema->getNonSearchableAttributeId(fieldName)); start.setTypedValue(attributeType, startString); end.setTypedValue(attributeType, endString); if(attributeType == ATTRIBUTE_TYPE_TIME){ // For time attributes gap should not be of the same type, it should be // of type TimeDuration. if(start > end){ // start should not be greater than end start = end; gap.setTypedValue(ATTRIBUTE_TYPE_DURATION, "00:00:00"); }else{ gap.setTypedValue(ATTRIBUTE_TYPE_DURATION, gapString); } }else{ if(start > end){ // start should not be greater than end start = end; gap.setTypedValue(attributeType , "0"); }else{ gap.setTypedValue(attributeType, gapString); } } } void FacetedSearchFilterInternal::doFilter(IndexSearcher *indexSearcher, const Query * query, QueryResults * input, QueryResults * output){ IndexSearcherInternal * indexSearcherInternal = dynamic_cast<IndexSearcherInternal *>(indexSearcher); Schema * schema = indexSearcherInternal->getSchema(); ForwardIndex * forwardIndex = indexSearcherInternal->getForwardIndex(); // first prepare internal structures based on the input preFilter(indexSearcher); // also copy all input results to output to save previous filter works output->copyForPostProcessing(input); // translate list of attribute names to list of attribute IDs std::vector<unsigned> attributeIds; for(std::vector<std::string>::iterator facetField = fields.begin(); facetField != fields.end() ; ++facetField){ attributeIds.push_back(schema->getNonSearchableAttributeId(*facetField)); } // move on the results once and do all facet calculations. for (std::vector<QueryResult *>::iterator resultIter = output->impl->sortedFinalResults.begin(); resultIter != output->impl->sortedFinalResults.end(); ++resultIter) { QueryResult * queryResult = *resultIter; // extract all facet related nonsearchable attribute values from this record // by accessing the forward index only once. bool isValid = false; const ForwardList * list = forwardIndex->getForwardList( queryResult->internalRecordId, isValid); ASSERT(isValid); const Byte * nonSearchableAttributesData = list->getNonSearchableAttributeContainerData(); // this vector is parallel to attributeIds vector std::vector<TypedValue> attributeDataValues; VariableLengthAttributeContainer::getBatchOfAttributes(attributeIds, schema,nonSearchableAttributesData, &attributeDataValues); // now iterate on attributes and incrementally update the facet results for(std::vector<std::string>::iterator facetField = fields.begin(); facetField != fields.end() ; ++facetField){ TypedValue & attributeValue = attributeDataValues.at( std::distance(fields.begin() , facetField)); // choose the type of aggregation for this attribute // increments the correct facet by one doProcessOneResult(attributeValue , std::distance(fields.begin() , facetField)); } } // now copy all results to output for(std::vector<std::pair< FacetType , FacetResultsContainer * > >::iterator facetResultsPtr = facetResults.begin(); facetResultsPtr != facetResults.end(); ++facetResultsPtr){ std::vector<std::pair< std::string, float > > results; facetResultsPtr->second->getNamesAndValues(results); output->impl->facetResults[fields.at(std::distance(facetResults.begin() , facetResultsPtr))] = std::make_pair(facetResultsPtr->first , results); } } void FacetedSearchFilterInternal::preFilter(IndexSearcher *indexSearcher){ IndexSearcherInternal * indexSearcherInternal = dynamic_cast<IndexSearcherInternal *>(indexSearcher); Schema * schema = indexSearcherInternal->getSchema(); for(std::vector<std::string>::iterator facetField = fields.begin(); facetField != fields.end() ; ++facetField){ FacetType facetType = facetTypes.at(std::distance(fields.begin() , facetField)); FacetHelper * facetHelper = NULL; FacetResultsContainer * facetResultsContainer = NULL; switch (facetType) { case FacetTypeCategorical: facetHelper = new CategoricalFacetHelper(); facetResultsContainer = new CategoricalFacetResultsContainer(); break; case FacetTypeRange: facetHelper = new RangeFacetHelper(); facetResultsContainer = new RangeFacetResultsContainer(); break; default: ASSERT(false); break; } std::string info[4]; info[0] = rangeStarts.at(std::distance(fields.begin() , facetField)); info[1] = rangeEnds.at(std::distance(fields.begin() , facetField)); info[2] = rangeGaps.at(std::distance(fields.begin() , facetField)); info[3] = *facetField; facetHelper->initialize(info , schema); facetResultsContainer->initialize(facetHelper , FacetAggregationTypeCount ); this->facetResults.push_back(std::make_pair(facetType , facetResultsContainer)); this->facetHelpers.push_back(facetHelper); } } void FacetedSearchFilterInternal::doProcessOneResult(const TypedValue & attributeValue, const unsigned facetFieldIndex){ std::pair<unsigned , std::string> idandName = this->facetHelpers.at(facetFieldIndex)->generateIDAndName(attributeValue); this->facetResults.at(facetFieldIndex).second->addResultToBucket(idandName.first , idandName.second , FacetAggregationTypeCount); } void FacetedSearchFilterInternal::initialize(std::vector<FacetType> & facetTypes, std::vector<std::string> & fields, std::vector<std::string> & rangeStarts, std::vector<std::string> & rangeEnds, std::vector<std::string> & rangeGaps){ this->fields = fields; this->facetTypes = facetTypes; this->rangeStarts = rangeStarts; this->rangeEnds = rangeEnds; this->rangeGaps = rangeGaps; } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ /* * This file includes unit tests for NetEQ. */ #include <stdio.h> #include <stdlib.h> #include <string.h> // memset #include <string> #include <vector> #include "gtest/gtest.h" #include "modules/audio_coding/neteq/test/NETEQTEST_CodecClass.h" #include "modules/audio_coding/neteq/test/NETEQTEST_NetEQClass.h" #include "modules/audio_coding/neteq/test/NETEQTEST_RTPpacket.h" #include "typedefs.h" // NOLINT(build/include) #include "modules/audio_coding/neteq/interface/webrtc_neteq.h" #include "modules/audio_coding/neteq/interface/webrtc_neteq_help_macros.h" #include "testsupport/fileutils.h" namespace webrtc { class NetEqDecodingTest : public ::testing::Test { protected: NetEqDecodingTest(); virtual void SetUp(); virtual void TearDown(); void SelectDecoders(WebRtcNetEQDecoder* used_codec); void LoadDecoders(); void DecodeAndCompare(const std::string &rtp_file, const std::string &ref_file); NETEQTEST_NetEQClass* neteq_inst_; std::vector<NETEQTEST_Decoder*> dec_; }; NetEqDecodingTest::NetEqDecodingTest() : neteq_inst_(NULL) {} void NetEqDecodingTest::SetUp() { WebRtcNetEQDecoder usedCodec[kDecoderReservedEnd - 1]; SelectDecoders(usedCodec); neteq_inst_ = new NETEQTEST_NetEQClass(usedCodec, dec_.size(), 8000, kTCPLargeJitter); ASSERT_TRUE(neteq_inst_); LoadDecoders(); } void NetEqDecodingTest::TearDown() { if (neteq_inst_) delete neteq_inst_; for (size_t i = 0; i < dec_.size(); ++i) { if (dec_[i]) delete dec_[i]; } } void NetEqDecodingTest::SelectDecoders(WebRtcNetEQDecoder* used_codec) { *used_codec++ = kDecoderPCMu; dec_.push_back(new decoder_PCMU(0)); *used_codec++ = kDecoderPCMa; dec_.push_back(new decoder_PCMA(8)); *used_codec++ = kDecoderILBC; dec_.push_back(new decoder_ILBC(102)); *used_codec++ = kDecoderISAC; dec_.push_back(new decoder_iSAC(103)); *used_codec++ = kDecoderISACswb; dec_.push_back(new decoder_iSACSWB(104)); *used_codec++ = kDecoderPCM16B; dec_.push_back(new decoder_PCM16B_NB(93)); *used_codec++ = kDecoderPCM16Bwb; dec_.push_back(new decoder_PCM16B_WB(94)); *used_codec++ = kDecoderPCM16Bswb32kHz; dec_.push_back(new decoder_PCM16B_SWB32(95)); *used_codec++ = kDecoderCNG; dec_.push_back(new decoder_CNG(13)); } void NetEqDecodingTest::LoadDecoders() { for (size_t i = 0; i < dec_.size(); ++i) { ASSERT_EQ(0, dec_[i]->loadToNetEQ(*neteq_inst_)); } } void NetEqDecodingTest::DecodeAndCompare(const std::string &rtp_file, const std::string &ref_file) { NETEQTEST_RTPpacket rtp; FILE* rtp_fp = fopen(rtp_file.c_str(), "rb"); ASSERT_TRUE(rtp_fp != NULL); ASSERT_EQ(0, NETEQTEST_RTPpacket::skipFileHeader(rtp_fp)); ASSERT_GT(rtp.readFromFile(rtp_fp), 0); FILE* ref_fp = NULL; FILE* out_fp = NULL; if (!ref_file.empty()) { ref_fp = fopen(ref_file.c_str(), "rb"); ASSERT_TRUE(ref_fp != NULL); } else { std::string out_file = webrtc::test::OutputPath() + "neteq_out.pcm"; out_fp = fopen(out_file.c_str(), "wb"); ASSERT_TRUE(out_fp != NULL); } unsigned int sim_clock = 0; // NetEQ must be polled for data once every 10 ms. Thus, neither of the // constants below can be changed. const int kTimeStepMs = 10; const int kBlockSize8kHz = kTimeStepMs * 8; const int kBlockSize16kHz = kTimeStepMs * 16; const int kBlockSize32kHz = kTimeStepMs * 32; const int kMaxBlockSize = kBlockSize32kHz; while (rtp.dataLen() >= 0) { // Check if time to receive. while ((sim_clock >= rtp.time()) && (rtp.dataLen() >= 0)) { if (rtp.dataLen() > 0) { ASSERT_EQ(0, neteq_inst_->recIn(rtp)); } // Get next packet. ASSERT_NE(-1, rtp.readFromFile(rtp_fp)); } // RecOut WebRtc_Word16 out_data[kMaxBlockSize]; WebRtc_Word16 out_len = neteq_inst_->recOut(out_data); ASSERT_TRUE((out_len == kBlockSize8kHz) || (out_len == kBlockSize16kHz) || (out_len == kBlockSize32kHz)); if (ref_fp) { // Read from ref file. WebRtc_Word16 ref_data[kMaxBlockSize]; if (static_cast<size_t>(out_len) != fread(ref_data, sizeof(WebRtc_Word16), out_len, ref_fp)) { break; } // Compare EXPECT_EQ(0, memcmp(out_data, ref_data, sizeof(WebRtc_Word16) * out_len)); } if (out_fp) { // Write to output file (mainly for generating new output vectors). ASSERT_EQ(static_cast<size_t>(out_len), fwrite(out_data, sizeof(WebRtc_Word16), out_len, out_fp)); } // Increase time. sim_clock += kTimeStepMs; } fclose(rtp_fp); if (ref_fp) { ASSERT_NE(0, feof(ref_fp)); // Make sure that we reached the end. fclose(ref_fp); } if (out_fp) fclose(out_fp); } #if defined(WEBRTC_LINUX) && defined(WEBRTC_ARCH_64_BITS) TEST_F(NetEqDecodingTest, TestBitExactness) { const std::string kInputRtpFile = webrtc::test::ProjectRootPath() + "test/data/audio_coding/universal.rtp"; const std::string kInputRefFile = webrtc::test::ProjectRootPath() + "test/data/audio_coding/universal_ref.pcm"; DecodeAndCompare(kInputRtpFile, kInputRefFile); } #endif // defined(WEBRTC_LINUX) && defined(WEBRTC_ARCH_64_BITS) } // namespace <commit_msg>Testing NetEQ network statistics<commit_after>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ /* * This file includes unit tests for NetEQ. */ #include <stdlib.h> #include <string.h> // memset #include <string> #include <vector> #include "gtest/gtest.h" #include "modules/audio_coding/neteq/interface/webrtc_neteq.h" #include "modules/audio_coding/neteq/interface/webrtc_neteq_help_macros.h" #include "modules/audio_coding/neteq/test/NETEQTEST_CodecClass.h" #include "modules/audio_coding/neteq/test/NETEQTEST_NetEQClass.h" #include "modules/audio_coding/neteq/test/NETEQTEST_RTPpacket.h" #include "testsupport/fileutils.h" #include "typedefs.h" // NOLINT(build/include) namespace webrtc { class RefFiles { public: RefFiles(const std::string& input_file, const std::string& output_file); ~RefFiles(); template<class T> void ProcessReference(const T& test_results); template<typename T, size_t n> void ProcessReference( const T (&test_results)[n], size_t length); template<typename T, size_t n> void WriteToFile( const T (&test_results)[n], size_t length); template<typename T, size_t n> void ReadFromFileAndCompare( const T (&test_results)[n], size_t length); void WriteToFile(const WebRtcNetEQ_NetworkStatistics& stats); void ReadFromFileAndCompare(const WebRtcNetEQ_NetworkStatistics& stats); void WriteToFile(const WebRtcNetEQ_RTCPStat& stats); void ReadFromFileAndCompare(const WebRtcNetEQ_RTCPStat& stats); FILE* input_fp_; FILE* output_fp_; }; RefFiles::RefFiles(const std::string &input_file, const std::string &output_file) : input_fp_(NULL), output_fp_(NULL) { if (!input_file.empty()) { input_fp_ = fopen(input_file.c_str(), "rb"); EXPECT_TRUE(input_fp_ != NULL); } if (!output_file.empty()) { output_fp_ = fopen(output_file.c_str(), "wb"); EXPECT_TRUE(output_fp_ != NULL); } } RefFiles::~RefFiles() { if (input_fp_) { EXPECT_EQ(EOF, fgetc(input_fp_)); // Make sure that we reached the end. fclose(input_fp_); } if (output_fp_) fclose(output_fp_); } template<class T> void RefFiles::ProcessReference(const T& test_results) { WriteToFile(test_results); ReadFromFileAndCompare(test_results); } template<typename T, size_t n> void RefFiles::ProcessReference(const T (&test_results)[n], size_t length) { WriteToFile(test_results, length); ReadFromFileAndCompare(test_results, length); } template<typename T, size_t n> void RefFiles::WriteToFile(const T (&test_results)[n], size_t length) { if (output_fp_) { ASSERT_EQ(length, fwrite(&test_results, sizeof(T), length, output_fp_)); } } template<typename T, size_t n> void RefFiles::ReadFromFileAndCompare(const T (&test_results)[n], size_t length) { if (input_fp_) { // Read from ref file. T* ref = new T[length]; ASSERT_EQ(length, fread(ref, sizeof(T), length, input_fp_)); // Compare EXPECT_EQ(0, memcmp(&test_results, ref, sizeof(T) * length)); delete [] ref; } } void RefFiles::WriteToFile(const WebRtcNetEQ_NetworkStatistics& stats) { if (output_fp_) { ASSERT_EQ(1u, fwrite(&stats, sizeof(WebRtcNetEQ_NetworkStatistics), 1, output_fp_)); } } void RefFiles::ReadFromFileAndCompare( const WebRtcNetEQ_NetworkStatistics& stats) { if (input_fp_) { // Read from ref file. size_t stat_size = sizeof(WebRtcNetEQ_NetworkStatistics); WebRtcNetEQ_NetworkStatistics ref_stats; ASSERT_EQ(1u, fread(&ref_stats, stat_size, 1, input_fp_)); // Compare EXPECT_EQ(0, memcmp(&stats, &ref_stats, stat_size)); } } void RefFiles::WriteToFile(const WebRtcNetEQ_RTCPStat& stats) { if (output_fp_) { ASSERT_EQ(1u, fwrite(&(stats.fraction_lost), sizeof(stats.fraction_lost), 1, output_fp_)); ASSERT_EQ(1u, fwrite(&(stats.cum_lost), sizeof(stats.cum_lost), 1, output_fp_)); ASSERT_EQ(1u, fwrite(&(stats.ext_max), sizeof(stats.ext_max), 1, output_fp_)); ASSERT_EQ(1u, fwrite(&(stats.jitter), sizeof(stats.jitter), 1, output_fp_)); } } void RefFiles::ReadFromFileAndCompare( const WebRtcNetEQ_RTCPStat& stats) { if (input_fp_) { // Read from ref file. WebRtcNetEQ_RTCPStat ref_stats; ASSERT_EQ(1u, fread(&(ref_stats.fraction_lost), sizeof(ref_stats.fraction_lost), 1, input_fp_)); ASSERT_EQ(1u, fread(&(ref_stats.cum_lost), sizeof(ref_stats.cum_lost), 1, input_fp_)); ASSERT_EQ(1u, fread(&(ref_stats.ext_max), sizeof(ref_stats.ext_max), 1, input_fp_)); ASSERT_EQ(1u, fread(&(ref_stats.jitter), sizeof(ref_stats.jitter), 1, input_fp_)); // Compare EXPECT_EQ(ref_stats.fraction_lost, stats.fraction_lost); EXPECT_EQ(ref_stats.cum_lost, stats.cum_lost); EXPECT_EQ(ref_stats.ext_max, stats.ext_max); EXPECT_EQ(ref_stats.jitter, stats.jitter); } } class NetEqDecodingTest : public ::testing::Test { protected: // NetEQ must be polled for data once every 10 ms. Thus, neither of the // constants below can be changed. static const int kTimeStepMs = 10; static const int kBlockSize8kHz = kTimeStepMs * 8; static const int kBlockSize16kHz = kTimeStepMs * 16; static const int kBlockSize32kHz = kTimeStepMs * 32; static const int kMaxBlockSize = kBlockSize32kHz; NetEqDecodingTest(); virtual void SetUp(); virtual void TearDown(); void SelectDecoders(WebRtcNetEQDecoder* used_codec); void LoadDecoders(); void OpenInputFile(const std::string &rtp_file); void Process(NETEQTEST_RTPpacket* rtp_ptr, int16_t* out_len); void DecodeAndCompare(const std::string &rtp_file, const std::string &ref_file); void DecodeAndCheckStats(const std::string &rtp_file, const std::string &stat_ref_file, const std::string &rtcp_ref_file); NETEQTEST_NetEQClass* neteq_inst_; std::vector<NETEQTEST_Decoder*> dec_; FILE* rtp_fp_; unsigned int sim_clock_; int16_t out_data_[kMaxBlockSize]; }; NetEqDecodingTest::NetEqDecodingTest() : neteq_inst_(NULL), rtp_fp_(NULL), sim_clock_(0) { memset(out_data_, 0, sizeof(out_data_)); } void NetEqDecodingTest::SetUp() { WebRtcNetEQDecoder usedCodec[kDecoderReservedEnd - 1]; SelectDecoders(usedCodec); neteq_inst_ = new NETEQTEST_NetEQClass(usedCodec, dec_.size(), 8000, kTCPLargeJitter); ASSERT_TRUE(neteq_inst_); LoadDecoders(); } void NetEqDecodingTest::TearDown() { if (neteq_inst_) delete neteq_inst_; for (size_t i = 0; i < dec_.size(); ++i) { if (dec_[i]) delete dec_[i]; } if (rtp_fp_) fclose(rtp_fp_); } void NetEqDecodingTest::SelectDecoders(WebRtcNetEQDecoder* used_codec) { *used_codec++ = kDecoderPCMu; dec_.push_back(new decoder_PCMU(0)); *used_codec++ = kDecoderPCMa; dec_.push_back(new decoder_PCMA(8)); *used_codec++ = kDecoderILBC; dec_.push_back(new decoder_ILBC(102)); *used_codec++ = kDecoderISAC; dec_.push_back(new decoder_iSAC(103)); *used_codec++ = kDecoderISACswb; dec_.push_back(new decoder_iSACSWB(104)); *used_codec++ = kDecoderPCM16B; dec_.push_back(new decoder_PCM16B_NB(93)); *used_codec++ = kDecoderPCM16Bwb; dec_.push_back(new decoder_PCM16B_WB(94)); *used_codec++ = kDecoderPCM16Bswb32kHz; dec_.push_back(new decoder_PCM16B_SWB32(95)); *used_codec++ = kDecoderCNG; dec_.push_back(new decoder_CNG(13)); } void NetEqDecodingTest::LoadDecoders() { for (size_t i = 0; i < dec_.size(); ++i) { ASSERT_EQ(0, dec_[i]->loadToNetEQ(*neteq_inst_)); } } void NetEqDecodingTest::OpenInputFile(const std::string &rtp_file) { rtp_fp_ = fopen(rtp_file.c_str(), "rb"); ASSERT_TRUE(rtp_fp_ != NULL); ASSERT_EQ(0, NETEQTEST_RTPpacket::skipFileHeader(rtp_fp_)); } void NetEqDecodingTest::Process(NETEQTEST_RTPpacket* rtp, int16_t* out_len) { // Check if time to receive. while ((sim_clock_ >= rtp->time()) && (rtp->dataLen() >= 0)) { if (rtp->dataLen() > 0) { ASSERT_EQ(0, neteq_inst_->recIn(*rtp)); } // Get next packet. ASSERT_NE(-1, rtp->readFromFile(rtp_fp_)); } // RecOut *out_len = neteq_inst_->recOut(out_data_); ASSERT_TRUE((*out_len == kBlockSize8kHz) || (*out_len == kBlockSize16kHz) || (*out_len == kBlockSize32kHz)); // Increase time. sim_clock_ += kTimeStepMs; } void NetEqDecodingTest::DecodeAndCompare(const std::string &rtp_file, const std::string &ref_file) { OpenInputFile(rtp_file); std::string ref_out_file = ""; if (ref_file.empty()) { ref_out_file = webrtc::test::OutputPath() + "neteq_out.pcm"; } RefFiles ref_files(ref_file, ref_out_file); NETEQTEST_RTPpacket rtp; ASSERT_GT(rtp.readFromFile(rtp_fp_), 0); while (rtp.dataLen() >= 0) { int16_t out_len; Process(&rtp, &out_len); ref_files.ProcessReference(out_data_, out_len); } } void NetEqDecodingTest::DecodeAndCheckStats(const std::string &rtp_file, const std::string &stat_ref_file, const std::string &rtcp_ref_file) { OpenInputFile(rtp_file); std::string stat_out_file = ""; if (stat_ref_file.empty()) { stat_out_file = webrtc::test::OutputPath() + "neteq_network_stats.dat"; } RefFiles network_stat_files(stat_ref_file, stat_out_file); std::string rtcp_out_file = ""; if (rtcp_ref_file.empty()) { rtcp_out_file = webrtc::test::OutputPath() + "neteq_rtcp_stats.dat"; } RefFiles rtcp_stat_files(rtcp_ref_file, rtcp_out_file); NETEQTEST_RTPpacket rtp; ASSERT_GT(rtp.readFromFile(rtp_fp_), 0); while (rtp.dataLen() >= 0) { int16_t out_len; Process(&rtp, &out_len); // Query the network statistics API once per second if (sim_clock_ % 1000 == 0) { // Process NetworkStatistics. WebRtcNetEQ_NetworkStatistics network_stats; ASSERT_EQ(0, WebRtcNetEQ_GetNetworkStatistics(neteq_inst_->instance(), &network_stats)); network_stat_files.ProcessReference(network_stats); // Process RTCPstat. WebRtcNetEQ_RTCPStat rtcp_stats; ASSERT_EQ(0, WebRtcNetEQ_GetRTCPStats(neteq_inst_->instance(), &rtcp_stats)); rtcp_stat_files.ProcessReference(rtcp_stats); } } } #if defined(WEBRTC_LINUX) && defined(WEBRTC_ARCH_64_BITS) TEST_F(NetEqDecodingTest, TestBitExactness) { const std::string kInputRtpFile = webrtc::test::ProjectRootPath() + "test/data/audio_coding/universal.rtp"; const std::string kInputRefFile = webrtc::test::ProjectRootPath() + "test/data/audio_coding/universal_ref.pcm"; DecodeAndCompare(kInputRtpFile, kInputRefFile); } #endif // defined(WEBRTC_LINUX) && defined(WEBRTC_ARCH_64_BITS) //TODO(hlundin): Add test target NetEqDecodingTest::TestNetworkStatistics. } // namespace <|endoftext|>
<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html #ifndef __BSE_CXXAUX_HH__ #define __BSE_CXXAUX_HH__ #include <sfi/sysconfig.h> #include <sys/types.h> // uint, ssize #include <cstdint> // uint64_t #include <memory> #include <vector> #include <map> namespace Bse { // == uint == #if BSE_SIZEOF_SYS_TYPESH_UINT == 0 typedef unsigned int uint; ///< Provide 'uint' if sys/types.h fails to do so. #else static_assert (BSE_SIZEOF_SYS_TYPESH_UINT == 4, ""); #endif static_assert (sizeof (uint) == 4, ""); // == type aliases == typedef uint8_t uint8; ///< An 8-bit unsigned integer. typedef uint16_t uint16; ///< A 16-bit unsigned integer. typedef uint32_t uint32; ///< A 32-bit unsigned integer. typedef uint64_t uint64; ///< A 64-bit unsigned integer, use PRI*64 in format strings. typedef int8_t int8; ///< An 8-bit signed integer. typedef int16_t int16; ///< A 16-bit signed integer. typedef int32_t int32; ///< A 32-bit signed integer. typedef int64_t int64; ///< A 64-bit unsigned integer, use PRI*64 in format strings. typedef uint32_t unichar; ///< A 32-bit unsigned integer used for Unicode characters. static_assert (sizeof (uint8) == 1 && sizeof (uint16) == 2 && sizeof (uint32) == 4 && sizeof (uint64) == 8, ""); static_assert (sizeof (int8) == 1 && sizeof (int16) == 2 && sizeof (int32) == 4 && sizeof (int64) == 8, ""); static_assert (sizeof (int) == 4 && sizeof (uint) == 4 && sizeof (unichar) == 4, ""); using std::map; using std::vector; typedef std::string String; ///< Convenience alias for std::string. typedef vector<String> StringVector; ///< Convenience alias for a std::vector<std::string>. // == Utility Macros == #define BSE_CPP_STRINGIFY(s) BSE_CPP_STRINGIFY_ (s) ///< Convert macro argument into a C const char*. #define BSE_CPP_STRINGIFY_(s) #s // Indirection helper, required to expand macros like __LINE__ #define BSE_CPP_PASTE2_(a,b) a ## b // Indirection helper, required to expand macros like __LINE__ #define BSE_CPP_PASTE2(a,b) BSE_CPP_PASTE2_ (a,b) ///< Paste two macro arguments into one C symbol name #define BSE_ISLIKELY(expr) __builtin_expect (bool (expr), 1) ///< Compiler hint to optimize for @a expr evaluating to true. #define BSE_UNLIKELY(expr) __builtin_expect (bool (expr), 0) ///< Compiler hint to optimize for @a expr evaluating to false. #define BSE_ABS(a) ((a) < 0 ? -(a) : (a)) ///< Yield the absolute value of @a a. #define BSE_MIN(a,b) ((a) <= (b) ? (a) : (b)) ///< Yield the smaller value of @a a and @a b. #define BSE_MAX(a,b) ((a) >= (b) ? (a) : (b)) ///< Yield the greater value of @a a and @a b. #define BSE_CLAMP(v,mi,ma) ((v) < (mi) ? (mi) : ((v) > (ma) ? (ma) : (v))) ///< Yield @a v clamped to [ @a mi .. @a ma ]. #define BSE_ARRAY_SIZE(array) (sizeof (array) / sizeof ((array)[0])) ///< Yield the number of C @a array elements. #define BSE_ALIGN(size, base) ((base) * ((size_t (size) + (base) - 1) / (base))) ///< Round up @a size to multiples of @a base. /// @addtogroup GCC Attributes /// Bse macros that are shorthands for <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attributes</a>. /// @{ #define BSE_ALWAYS_INLINE __attribute__ ((always_inline)) #define BSE_COLD __attribute__ ((__cold__)) #define BSE_CONST __attribute__ ((__const__)) #define BSE_CONSTRUCTOR __attribute__ ((constructor,used)) // gcc-3.3 also needs "used" to emit code #define BSE_DEPRECATED __attribute__ ((__deprecated__)) #define BSE_FORMAT(fx) __attribute__ ((__format_arg__ (fx))) #define BSE_HOT __attribute__ ((__hot__)) #define BSE_MALLOC __attribute__ ((__malloc__)) #define BSE_MAY_ALIAS __attribute__ ((may_alias)) #define BSE_NOINLINE __attribute__ ((noinline)) #define BSE_NORETURN __attribute__ ((__noreturn__)) #define BSE_NO_INSTRUMENT __attribute__ ((__no_instrument_function__)) #define BSE_PRINTF(fx, ax) __attribute__ ((__format__ (__printf__, fx, ax))) #define BSE_PURE __attribute__ ((__pure__)) #define BSE_SCANF(fx, ax) __attribute__ ((__format__ (__scanf__, fx, ax))) #define BSE_SENTINEL __attribute__ ((__sentinel__)) #define BSE_UNUSED __attribute__ ((__unused__)) #define BSE_USE_RESULT __attribute__ ((warn_unused_result)) #define BSE_USED __attribute__ ((__used__)) #define BSE_WEAK __attribute__ ((__weak__)) /// @} /// Return silently if @a cond does not evaluate to true, with return value @a ... #define BSE_RETURN_UNLESS(cond, ...) do { if (BSE_UNLIKELY (!bool (cond))) return __VA_ARGS__; } while (0) /// Delete copy ctor and assignment operator. #define BSE_CLASS_NON_COPYABLE(ClassName) \ /*copy-ctor*/ ClassName (const ClassName&) = delete; \ ClassName& operator= (const ClassName&) = delete #ifdef __clang__ // clang++-3.8.0: work around 'variable length array of non-POD element type' #define BSE_DECLARE_VLA(Type, var, count) std::vector<Type> var (count) #else // sane c++ #define BSE_DECLARE_VLA(Type, var, count) Type var[count] ///< Declare a variable length array (clang++ uses std::vector<>). #endif /** * A std::make_shared<>() wrapper class to access private ctor & dtor. * To call std::make_shared<T>() on a class @a T, its constructor and * destructor must be public. For classes with private or protected * constructor or destructor, this class can be used as follows: * @code{.cc} * class Type { * Type (ctor_args...); // Private ctor. * friend class FriendAllocator<Type>; // Allow access to ctor/dtor of Type. * }; * std::shared_ptr<Type> t = FriendAllocator<Type>::make_shared (ctor_args...); * @endcode */ template<class T> class FriendAllocator : public std::allocator<T> { public: /// Construct type @a C object, standard allocator requirement. template<typename C, typename... Args> static inline void construct (C *p, Args &&... args) { ::new ((void*) p) C (std::forward<Args> (args)...); } /// Delete type @a C object, standard allocator requirement. template<typename C> static inline void destroy (C *p) { p->~C (); } /** * Construct an object of type @a T that is wrapped into a std::shared_ptr<T>. * @param args The list of arguments to pass into a T() constructor. * @return A std::shared_ptr<T> owning the newly created object. */ template<typename ...Args> static inline std::shared_ptr<T> make_shared (Args &&... args) { return std::allocate_shared<T> (FriendAllocator(), std::forward<Args> (args)...); } }; /** Shorthand for std::dynamic_pointer_cast<>(shared_from_this()). * A shared_ptr_cast() takes a std::shared_ptr or a pointer to an @a object that * supports std::enable_shared_from_this::shared_from_this(). * Using std::dynamic_pointer_cast(), the shared_ptr passed in (or retrieved via * calling shared_from_this()) is cast into a std::shared_ptr<@a Target>, possibly * resulting in an empty (NULL) std::shared_ptr if the underlying dynamic_cast() * was not successful or if a NULL @a object was passed in. * Note that shared_from_this() can throw a std::bad_weak_ptr exception if * the object has no associated std::shared_ptr (usually during ctor and dtor), in * which case the exception will also be thrown from shared_ptr_cast<Target>(). * However a shared_ptr_cast<Target*>() call will not throw and yield an empty * (NULL) std::shared_ptr<@a Target>. This is analogous to dynamic_cast<T@amp> which * throws, versus dynamic_cast<T*> which yields NULL. * @return A std::shared_ptr<@a Target> storing a pointer to @a object or NULL. * @throws std::bad_weak_ptr if shared_from_this() throws, unless the @a Target* form is used. */ template<class Target, class Source> std::shared_ptr<typename std::remove_pointer<Target>::type> shared_ptr_cast (Source *object) { if (!object) return NULL; // construct shared_ptr if possible typedef decltype (object->shared_from_this()) ObjectP; ObjectP sptr; if (std::is_pointer<Target>::value) try { sptr = object->shared_from_this(); } catch (const std::bad_weak_ptr&) { return NULL; } else // for non-pointers, allow bad_weak_ptr exceptions sptr = object->shared_from_this(); // cast into target shared_ptr<> type return std::dynamic_pointer_cast<typename std::remove_pointer<Target>::type> (sptr); } /// See shared_ptr_cast(Source*). template<class Target, class Source> const std::shared_ptr<typename std::remove_pointer<Target>::type> shared_ptr_cast (const Source *object) { return shared_ptr_cast<Target> (const_cast<Source*> (object)); } /// See shared_ptr_cast(Source*). template<class Target, class Source> std::shared_ptr<typename std::remove_pointer<Target>::type> shared_ptr_cast (std::shared_ptr<Source> &sptr) { return std::dynamic_pointer_cast<typename std::remove_pointer<Target>::type> (sptr); } /// See shared_ptr_cast(Source*). template<class Target, class Source> const std::shared_ptr<typename std::remove_pointer<Target>::type> shared_ptr_cast (const std::shared_ptr<Source> &sptr) { return shared_ptr_cast<Target> (const_cast<std::shared_ptr<Source>&> (sptr)); } } // Bse #endif // __BSE_CXXAUX_HH__ <commit_msg>SFI: cxxaux: add type-safe new_inplace and delete_inplace<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html #ifndef __BSE_CXXAUX_HH__ #define __BSE_CXXAUX_HH__ #include <sfi/sysconfig.h> #include <sys/types.h> // uint, ssize #include <cstdint> // uint64_t #include <memory> #include <vector> #include <map> namespace Bse { // == uint == #if BSE_SIZEOF_SYS_TYPESH_UINT == 0 typedef unsigned int uint; ///< Provide 'uint' if sys/types.h fails to do so. #else static_assert (BSE_SIZEOF_SYS_TYPESH_UINT == 4, ""); #endif static_assert (sizeof (uint) == 4, ""); // == type aliases == typedef uint8_t uint8; ///< An 8-bit unsigned integer. typedef uint16_t uint16; ///< A 16-bit unsigned integer. typedef uint32_t uint32; ///< A 32-bit unsigned integer. typedef uint64_t uint64; ///< A 64-bit unsigned integer, use PRI*64 in format strings. typedef int8_t int8; ///< An 8-bit signed integer. typedef int16_t int16; ///< A 16-bit signed integer. typedef int32_t int32; ///< A 32-bit signed integer. typedef int64_t int64; ///< A 64-bit unsigned integer, use PRI*64 in format strings. typedef uint32_t unichar; ///< A 32-bit unsigned integer used for Unicode characters. static_assert (sizeof (uint8) == 1 && sizeof (uint16) == 2 && sizeof (uint32) == 4 && sizeof (uint64) == 8, ""); static_assert (sizeof (int8) == 1 && sizeof (int16) == 2 && sizeof (int32) == 4 && sizeof (int64) == 8, ""); static_assert (sizeof (int) == 4 && sizeof (uint) == 4 && sizeof (unichar) == 4, ""); using std::map; using std::vector; typedef std::string String; ///< Convenience alias for std::string. typedef vector<String> StringVector; ///< Convenience alias for a std::vector<std::string>. // == Utility Macros == #define BSE_CPP_STRINGIFY(s) BSE_CPP_STRINGIFY_ (s) ///< Convert macro argument into a C const char*. #define BSE_CPP_STRINGIFY_(s) #s // Indirection helper, required to expand macros like __LINE__ #define BSE_CPP_PASTE2_(a,b) a ## b // Indirection helper, required to expand macros like __LINE__ #define BSE_CPP_PASTE2(a,b) BSE_CPP_PASTE2_ (a,b) ///< Paste two macro arguments into one C symbol name #define BSE_ISLIKELY(expr) __builtin_expect (bool (expr), 1) ///< Compiler hint to optimize for @a expr evaluating to true. #define BSE_UNLIKELY(expr) __builtin_expect (bool (expr), 0) ///< Compiler hint to optimize for @a expr evaluating to false. #define BSE_ABS(a) ((a) < 0 ? -(a) : (a)) ///< Yield the absolute value of @a a. #define BSE_MIN(a,b) ((a) <= (b) ? (a) : (b)) ///< Yield the smaller value of @a a and @a b. #define BSE_MAX(a,b) ((a) >= (b) ? (a) : (b)) ///< Yield the greater value of @a a and @a b. #define BSE_CLAMP(v,mi,ma) ((v) < (mi) ? (mi) : ((v) > (ma) ? (ma) : (v))) ///< Yield @a v clamped to [ @a mi .. @a ma ]. #define BSE_ARRAY_SIZE(array) (sizeof (array) / sizeof ((array)[0])) ///< Yield the number of C @a array elements. #define BSE_ALIGN(size, base) ((base) * ((size_t (size) + (base) - 1) / (base))) ///< Round up @a size to multiples of @a base. /// @addtogroup GCC Attributes /// Bse macros that are shorthands for <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attributes</a>. /// @{ #define BSE_ALWAYS_INLINE __attribute__ ((always_inline)) #define BSE_COLD __attribute__ ((__cold__)) #define BSE_CONST __attribute__ ((__const__)) #define BSE_CONSTRUCTOR __attribute__ ((constructor,used)) // gcc-3.3 also needs "used" to emit code #define BSE_DEPRECATED __attribute__ ((__deprecated__)) #define BSE_FORMAT(fx) __attribute__ ((__format_arg__ (fx))) #define BSE_HOT __attribute__ ((__hot__)) #define BSE_MALLOC __attribute__ ((__malloc__)) #define BSE_MAY_ALIAS __attribute__ ((may_alias)) #define BSE_NOINLINE __attribute__ ((noinline)) #define BSE_NORETURN __attribute__ ((__noreturn__)) #define BSE_NO_INSTRUMENT __attribute__ ((__no_instrument_function__)) #define BSE_PRINTF(fx, ax) __attribute__ ((__format__ (__printf__, fx, ax))) #define BSE_PURE __attribute__ ((__pure__)) #define BSE_SCANF(fx, ax) __attribute__ ((__format__ (__scanf__, fx, ax))) #define BSE_SENTINEL __attribute__ ((__sentinel__)) #define BSE_UNUSED __attribute__ ((__unused__)) #define BSE_USE_RESULT __attribute__ ((warn_unused_result)) #define BSE_USED __attribute__ ((__used__)) #define BSE_WEAK __attribute__ ((__weak__)) /// @} /// Return silently if @a cond does not evaluate to true, with return value @a ... #define BSE_RETURN_UNLESS(cond, ...) do { if (BSE_UNLIKELY (!bool (cond))) return __VA_ARGS__; } while (0) /// Delete copy ctor and assignment operator. #define BSE_CLASS_NON_COPYABLE(ClassName) \ /*copy-ctor*/ ClassName (const ClassName&) = delete; \ ClassName& operator= (const ClassName&) = delete #ifdef __clang__ // clang++-3.8.0: work around 'variable length array of non-POD element type' #define BSE_DECLARE_VLA(Type, var, count) std::vector<Type> var (count) #else // sane c++ #define BSE_DECLARE_VLA(Type, var, count) Type var[count] ///< Declare a variable length array (clang++ uses std::vector<>). #endif /// Call inplace new operator by automatically inferring the Type. template<class Type, class ...Ts> __attribute__ ((always_inline)) inline void new_inplace (Type &typemem, Ts &&... args) { new (&typemem) Type (std::forward<Ts> (args)...); } /// Call inplace delete operator by automatically inferring the Type. template<class Type> __attribute__ ((always_inline)) inline void delete_inplace (Type &typemem) { typemem.~Type(); } /** * A std::make_shared<>() wrapper class to access private ctor & dtor. * To call std::make_shared<T>() on a class @a T, its constructor and * destructor must be public. For classes with private or protected * constructor or destructor, this class can be used as follows: * @code{.cc} * class Type { * Type (ctor_args...); // Private ctor. * friend class FriendAllocator<Type>; // Allow access to ctor/dtor of Type. * }; * std::shared_ptr<Type> t = FriendAllocator<Type>::make_shared (ctor_args...); * @endcode */ template<class T> class FriendAllocator : public std::allocator<T> { public: /// Construct type @a C object, standard allocator requirement. template<typename C, typename... Args> static inline void construct (C *p, Args &&... args) { ::new ((void*) p) C (std::forward<Args> (args)...); } /// Delete type @a C object, standard allocator requirement. template<typename C> static inline void destroy (C *p) { p->~C (); } /** * Construct an object of type @a T that is wrapped into a std::shared_ptr<T>. * @param args The list of arguments to pass into a T() constructor. * @return A std::shared_ptr<T> owning the newly created object. */ template<typename ...Args> static inline std::shared_ptr<T> make_shared (Args &&... args) { return std::allocate_shared<T> (FriendAllocator(), std::forward<Args> (args)...); } }; /** Shorthand for std::dynamic_pointer_cast<>(shared_from_this()). * A shared_ptr_cast() takes a std::shared_ptr or a pointer to an @a object that * supports std::enable_shared_from_this::shared_from_this(). * Using std::dynamic_pointer_cast(), the shared_ptr passed in (or retrieved via * calling shared_from_this()) is cast into a std::shared_ptr<@a Target>, possibly * resulting in an empty (NULL) std::shared_ptr if the underlying dynamic_cast() * was not successful or if a NULL @a object was passed in. * Note that shared_from_this() can throw a std::bad_weak_ptr exception if * the object has no associated std::shared_ptr (usually during ctor and dtor), in * which case the exception will also be thrown from shared_ptr_cast<Target>(). * However a shared_ptr_cast<Target*>() call will not throw and yield an empty * (NULL) std::shared_ptr<@a Target>. This is analogous to dynamic_cast<T@amp> which * throws, versus dynamic_cast<T*> which yields NULL. * @return A std::shared_ptr<@a Target> storing a pointer to @a object or NULL. * @throws std::bad_weak_ptr if shared_from_this() throws, unless the @a Target* form is used. */ template<class Target, class Source> std::shared_ptr<typename std::remove_pointer<Target>::type> shared_ptr_cast (Source *object) { if (!object) return NULL; // construct shared_ptr if possible typedef decltype (object->shared_from_this()) ObjectP; ObjectP sptr; if (std::is_pointer<Target>::value) try { sptr = object->shared_from_this(); } catch (const std::bad_weak_ptr&) { return NULL; } else // for non-pointers, allow bad_weak_ptr exceptions sptr = object->shared_from_this(); // cast into target shared_ptr<> type return std::dynamic_pointer_cast<typename std::remove_pointer<Target>::type> (sptr); } /// See shared_ptr_cast(Source*). template<class Target, class Source> const std::shared_ptr<typename std::remove_pointer<Target>::type> shared_ptr_cast (const Source *object) { return shared_ptr_cast<Target> (const_cast<Source*> (object)); } /// See shared_ptr_cast(Source*). template<class Target, class Source> std::shared_ptr<typename std::remove_pointer<Target>::type> shared_ptr_cast (std::shared_ptr<Source> &sptr) { return std::dynamic_pointer_cast<typename std::remove_pointer<Target>::type> (sptr); } /// See shared_ptr_cast(Source*). template<class Target, class Source> const std::shared_ptr<typename std::remove_pointer<Target>::type> shared_ptr_cast (const std::shared_ptr<Source> &sptr) { return shared_ptr_cast<Target> (const_cast<std::shared_ptr<Source>&> (sptr)); } } // Bse #endif // __BSE_CXXAUX_HH__ <|endoftext|>
<commit_before>#include "mainwindow.h" #include "pagefactory.h" #include "dcppage.h" #include <duinavigationbar.h> #include <duideviceprofile.h> MainWindow::MainWindow() { connect(navigationBar(), SIGNAL(homeClicked()), this, SLOT(homeClicked())); connect(navigationBar(), SIGNAL(backClicked()), this, SLOT(backClicked())); Pages::Handle handle = {Pages::MAIN, ""}; changePage(handle); } void MainWindow::homeClicked() { // changePage(Pages::MAIN); onRotateClicked(); } void MainWindow::backClicked() { DcpPage* page = PageFactory::page(currentPage()); changePage(page->referer()); } MainWindow::~MainWindow() { } void MainWindow::changePage(Pages::Handle handle) { if (handle.id == Pages::NOPAGE) return; DcpPage* page = PageFactory::instance()->create(handle.id, handle.param); // addPage(page); connect (page, SIGNAL(openSubPage(Pages::Handle)), this, SLOT(changePage(Pages::Handle))); qDebug() << Q_FUNC_INFO; DcpPage* oldPage = PageFactory::page(currentPage()); if (oldPage) { if (page->referer().id == Pages::NOPAGE) page->setReferer(oldPage->handle()); // removePage(oldPage); } page->handle().id == Pages::MAIN ? navigationBar()->showCloseButton() : navigationBar()->showBackButton(); // showPage(page); page->appearNow(); } void MainWindow::onRotateClicked() { DuiDeviceProfile *profile = DuiDeviceProfile::instance(); // m_Category->onOrientationChange(profile->orientation()); if ( profile->orientation() == Dui::Portrait ) { qDebug() << "mode changes to Angle0"; profile->setOrientationAngle (DuiDeviceProfile::Angle0); } else { qDebug() << "mode changes to Angle90"; profile->setOrientationAngle (DuiDeviceProfile::Angle90); } } <commit_msg>adjusting to DuiApplicationPage changes<commit_after>#include "mainwindow.h" #include "pagefactory.h" #include "dcppage.h" #include <duinavigationbar.h> #include <duideviceprofile.h> MainWindow::MainWindow() { connect(navigationBar(), SIGNAL(homeClicked()), this, SLOT(homeClicked())); connect(navigationBar(), SIGNAL(backClicked()), this, SLOT(backClicked())); Pages::Handle handle = {Pages::MAIN, ""}; changePage(handle); } void MainWindow::homeClicked() { // changePage(Pages::MAIN); onRotateClicked(); } void MainWindow::backClicked() { DcpPage* page = PageFactory::page(currentPage()); changePage(page->referer()); } MainWindow::~MainWindow() { } void MainWindow::changePage(Pages::Handle handle) { if (handle.id == Pages::NOPAGE) return; DcpPage* page = PageFactory::instance()->create(handle.id, handle.param); connect (page, SIGNAL(openSubPage(Pages::Handle)), this, SLOT(changePage(Pages::Handle))); qDebug() << Q_FUNC_INFO; DcpPage* oldPage = PageFactory::page(currentPage()); if (oldPage) { if (page->referer().id == Pages::NOPAGE) page->setReferer(oldPage->handle()); oldPage->dissappearNow(); } page->handle().id == Pages::MAIN ? navigationBar()->showCloseButton() : navigationBar()->showBackButton(); page->appearNow(DuiSceneWindow::DestroyWhenDone); } void MainWindow::onRotateClicked() { DuiDeviceProfile *profile = DuiDeviceProfile::instance(); // m_Category->onOrientationChange(profile->orientation()); if ( profile->orientation() == Dui::Portrait ) { qDebug() << "mode changes to Angle0"; profile->setOrientationAngle (DuiDeviceProfile::Angle0); } else { qDebug() << "mode changes to Angle90"; profile->setOrientationAngle (DuiDeviceProfile::Angle90); } } <|endoftext|>
<commit_before>#pragma once #include <utility> #include <vector> #include <cmath> #include <fstream> #include <iomanip> #include "derivative.hpp" namespace fp { template<typename Func, typename Float> std::tuple<std::vector<Float>, int, std::vector<Float>> fixed_point(const Func& g, Float x0, Float abstol) { // vector to store intermediate x_i values std::vector<Float> xvec; std::vector<Float> rvec; // vector of rate approximations // do the first iteration outside the while loop xvec.push_back(g(x0)); Float currtol = static_cast<Float>(std::abs(xvec[0] - x0)); // number of iterations : we have already performed one auto i = 1; Float rate = NAN; rvec.push_back(rate); Float x_iminus1; Float x_i; Float x_iplus1; Float deltaxp1; while (currtol > abstol) { x_iminus1 = xvec[i - 1]; x_i = g(x_iminus1); xvec.push_back(x_i); // xi = g(x_{i - 1}) x_iplus1 = g(x_i); currtol = std::abs(x_i - x_iminus1); deltaxp1 = std::abs(x_iplus1 - x_i); if ((i - 2) > 0) { rate = std::log(deltaxp1 / currtol) / std::log(currtol / std::abs(x_iminus1 - xvec[i - 2])); rvec.push_back(rate); } else { rvec.push_back(NAN); } ++i; } return std::make_tuple(xvec, i, rvec); } template<typename T> void printElement(T t, const int& width, std::ostream& stream) { static const char separator = ' '; stream << std::left << std::setw(width) << std::setfill(separator) << t; } template<typename Func, typename Float> void test_fixed_point(const Func& g, Float x0, Float abstol, const std::string& funcname = "g", const std::string& filename = "test_g.txt") { const int nameWidth = 24; const int numWidth = 25; std::ofstream file; file.open(filename.c_str(), std::ios::out | std::ios::app); file << std::scientific << std::setprecision(15); file << "Getting the fixed points of '" << funcname << "' given x_0 = " << x0 << " and abstol = " << abstol << std::endl; auto tuple = fixed_point(g, x0, abstol); auto xvec = std::get<0>(tuple); auto iters = std::get<1>(tuple); auto rvec = std::get<2>(tuple); printElement("i", nameWidth, file); printElement("x_i", nameWidth, file); printElement("|x_i - x_{i - 1}|", nameWidth, file); printElement("rate", nameWidth, file); file << '\n'; for (auto i = 0; i < xvec.size(); ++i) { printElement(i, numWidth, file); printElement(xvec[i], numWidth, file); if ((i - 1) >= 0) { printElement(std::abs(xvec[i] - xvec[i - 1]), numWidth, file); } printElement(rvec[i], numWidth, file); file << '\n'; } file << "END" << std::endl; } void test_fp(double x0, double abstol) { const auto g1 = [](double x) -> double { return (x * x + 2) / 3; }; // will result in NaNs because the value under the square root // will become negative at some point. const auto g2 = [](double x) -> double { return std::sqrt(3 * x - 2); }; const auto g3 = [](double x) -> double { return 3 - (2 / x); }; const auto g4 = [](double x) -> double { return (x * x - 2) / (2 * x - 3); }; std::vector<std::function<double(double)>> vec {g1, g2, g3, g4}; std::vector<std::string> filenames {"g1.txt", "g2.txt", "g3.txt", "g4.txt"}; std::vector<std::string> funcnames {"g1", "g2", "g3", "g4"}; for (auto i = 0; i < vec.size(); ++i) { fp::test_fixed_point(vec[i], x0, abstol, funcnames[i], filenames[i]); } } template<typename Func, typename Float> std::tuple<std::vector<Float>, int, std::vector<Float>> newton_method(const Func& f, Float x0, Float abstol) { // vector to store intermediate x_i values std::vector<Float> xvec; std::vector<Float> rvec; // vector of rate approximations // do the first iteration outside the while loop auto x1 = x0 - (f(x0) / derivative(f, x0)); xvec.push_back(x1); Float currtol = static_cast<Float>(std::abs(xvec[0] - x0)); // number of iterations : we have already performed one auto i = 1; Float rate = NAN; rvec.push_back(rate); Float x_iminus1; Float x_i; Float x_iplus1; Float deltaxp1; while (currtol > abstol) { x_iminus1 = xvec[i - 1]; x_i = x_iminus1 - (f(x_iminus1) / derivative(f, x_iminus1)); xvec.push_back(x_i); x_iplus1 = x_i - (f(x_i) / derivative(f, x_i)); currtol = std::abs(x_i - x_iminus1); deltaxp1 = std::abs(x_iplus1 - x_i); if ((i - 2) > 0) { rate = std::log(deltaxp1 / currtol) / std::log(currtol / std::abs(x_iminus1 - xvec[i - 2])); rvec.push_back(rate); } else { rvec.push_back(NAN); } ++i; } return std::make_tuple(xvec, i, rvec); } template<typename Func, typename Float> void test_newton_method(const Func& f, Float x0, Float abstol, const std::string& funcname = "f", const std::string& filename = "test_f.txt") { const int nameWidth = 24; const int numWidth = 25; std::ofstream file; file.open(filename.c_str(), std::ios::out | std::ios::app); file << std::scientific << std::setprecision(15); file << "Getting the fixed points of '" << funcname << "' given x_0 = " << x0 << " and abstol = " << abstol << std::endl; auto tuple = newton_method(f, x0, abstol); auto xvec = std::get<0>(tuple); auto iters = std::get<1>(tuple); auto rvec = std::get<2>(tuple); printElement("i", nameWidth, file); printElement("x_i", nameWidth, file); printElement("|x_i - x_{i - 1}|", nameWidth, file); printElement("rate", nameWidth, file); file << '\n'; for (auto i = 0; i < xvec.size(); ++i) { printElement(i, numWidth, file); printElement(xvec[i], numWidth, file); if ((i - 1) >= 0) { printElement(std::abs(xvec[i] - xvec[i - 1]), numWidth, file); } printElement(rvec[i], numWidth, file); file << '\n'; } file << "END" << std::endl; } namespace newton { // we can't use functors with the derivative function // so we have to stick to traditional functions double f1(double x) { return x * x - 3 * x + 2; } double f2(double x) { return x * x * x - 2 * x - 5; } double f3(double x) { return std::exp(-x) - x; } double f4(double x) { return std::sin(x) * x - 1; } double f5(double x) { return x * x * x - 3 * x * x + 3 * x - 1; } } void test_newton(double abstol) { using namespace newton; // for functions f1 to f5 std::vector<double (*)(double)> vec {f1, f2, f3, f4, f5}; std::vector<std::string> filenames {"f1.txt", "f2.txt", "f3.txt", "f4.txt", "f5.txt"}; std::vector<std::string> funcnames {"f1", "f2", "f3", "f4", "f5"}; std::vector<double> xnaughts {2.1, 2.5, 0.6, 0.9, 0.5}; for (auto i = 0; i < vec.size(); ++i) { test_newton_method(*vec[i], xnaughts[i], abstol, funcnames[i], filenames[i]); } } template<typename Func, typename Float> std::tuple<std::vector<Float>, int, std::vector<Float>> secant_method(const Func& f, Float x0, Float x1, Float abstol) { // vector to store intermediate x_i values std::vector<Float> xvec; std::vector<Float> rvec; // vector of rate approximations // do the first iteration outside the while loop xvec.push_back(x1); auto x2 = x1 - f(x1) * ((x1 - x0) / (f(x1) - f(x0))); xvec.push_back(x2); Float currtol = static_cast<Float>(std::abs(xvec[0] - x1)); // number of iterations : we have already performed one auto i = 2; Float rate = NAN; rvec.push_back(rate); Float x_iminus2; Float x_iminus1; Float x_i; Float x_iplus1; Float deltaxp1; while (currtol > abstol) { x_iminus2 = xvec[i - 2]; x_iminus1 = xvec[i - 1]; x_i = x_iminus1 - f(x_iminus1) * ((x_iminus1 - x_iminus2) / (f(x_iminus1) - f(x_iminus2))); xvec.push_back(x_i); x_iplus1 = x_i - f(x_i) * ((x_i - x_iminus1) / (f(x_i) - f(x_iminus1))); currtol = std::abs(x_i - x_iminus1); deltaxp1 = std::abs(x_iplus1 - x_i); if ((i - 2) > 0) { rate = std::log(deltaxp1 / currtol) / std::log(currtol / std::abs(x_iminus1 - xvec[i - 2])); rvec.push_back(rate); } else { rvec.push_back(NAN); } ++i; } return std::make_tuple(xvec, i, rvec); } template<typename Float, typename = std::enable_if<std::is_arithmetic<Float>::value>::type> Float midpoint(Float a, Float b) { return a + (b - a) / 2; } template<typename Float, typename = std::enable_if<std::is_arithmetic<Float>::value>::type> int sign(Float a) { return a > 0 ? 1 : -1; } template<typename Func, typename Float> Float bisection_method(const Func& f, Float a, Float b, Float abstol, int numiters) { auto n = 1; Float c; Float l = a; Float u = b; while (n <= numiters) { c = midpoint(l, u); if ((u - l) < abstol) { break; } if (sign(f(c)) = sign(f(l))) { l = c; } else { b = c; } n++; } return c; } }<commit_msg>There was a bug in the if statement of bisection. Also added the secant method testing code. Maybe we can refactor all of this.<commit_after>#pragma once #include <utility> #include <vector> #include <cmath> #include <fstream> #include <iomanip> #include "derivative.hpp" namespace fp { template<typename Func, typename Float> std::tuple<std::vector<Float>, int, std::vector<Float>> fixed_point(const Func& g, Float x0, Float abstol) { // vector to store intermediate x_i values std::vector<Float> xvec; std::vector<Float> rvec; // vector of rate approximations // do the first iteration outside the while loop xvec.push_back(g(x0)); Float currtol = static_cast<Float>(std::abs(xvec[0] - x0)); // number of iterations : we have already performed one auto i = 1; Float rate = NAN; rvec.push_back(rate); Float x_iminus1; Float x_i; Float x_iplus1; Float deltaxp1; while (currtol > abstol) { x_iminus1 = xvec[i - 1]; x_i = g(x_iminus1); xvec.push_back(x_i); // xi = g(x_{i - 1}) x_iplus1 = g(x_i); currtol = std::abs(x_i - x_iminus1); deltaxp1 = std::abs(x_iplus1 - x_i); if ((i - 2) > 0) { rate = std::log(deltaxp1 / currtol) / std::log(currtol / std::abs(x_iminus1 - xvec[i - 2])); rvec.push_back(rate); } else { rvec.push_back(NAN); } ++i; } return std::make_tuple(xvec, i, rvec); } template<typename T> void printElement(T t, const int& width, std::ostream& stream) { static const char separator = ' '; stream << std::left << std::setw(width) << std::setfill(separator) << t; } template<typename Func, typename Float> void test_fixed_point(const Func& g, Float x0, Float abstol, const std::string& funcname = "g", const std::string& filename = "test_g.txt") { const int nameWidth = 24; const int numWidth = 25; std::ofstream file; file.open(filename.c_str(), std::ios::out | std::ios::app); file << std::scientific << std::setprecision(15); file << "Getting the fixed points of '" << funcname << "' given x_0 = " << x0 << " and abstol = " << abstol << std::endl; auto tuple = fixed_point(g, x0, abstol); auto xvec = std::get<0>(tuple); auto iters = std::get<1>(tuple); auto rvec = std::get<2>(tuple); printElement("i", nameWidth, file); printElement("x_i", nameWidth, file); printElement("|x_i - x_{i - 1}|", nameWidth, file); printElement("rate", nameWidth, file); file << '\n'; for (auto i = 0; i < xvec.size(); ++i) { printElement(i, numWidth, file); printElement(xvec[i], numWidth, file); if ((i - 1) >= 0) { printElement(std::abs(xvec[i] - xvec[i - 1]), numWidth, file); } printElement(rvec[i], numWidth, file); file << '\n'; } file << "END" << std::endl; } void test_fp(double x0, double abstol) { const auto g1 = [](double x) -> double { return (x * x + 2) / 3; }; // will result in NaNs because the value under the square root // will become negative at some point. const auto g2 = [](double x) -> double { return std::sqrt(3 * x - 2); }; const auto g3 = [](double x) -> double { return 3 - (2 / x); }; const auto g4 = [](double x) -> double { return (x * x - 2) / (2 * x - 3); }; std::vector<std::function<double(double)>> vec {g1, g2, g3, g4}; std::vector<std::string> filenames {"g1.txt", "g2.txt", "g3.txt", "g4.txt"}; std::vector<std::string> funcnames {"g1", "g2", "g3", "g4"}; for (auto i = 0; i < vec.size(); ++i) { fp::test_fixed_point(vec[i], x0, abstol, funcnames[i], filenames[i]); } } template<typename Func, typename Float> std::tuple<std::vector<Float>, int, std::vector<Float>> newton_method(const Func& f, Float x0, Float abstol) { // vector to store intermediate x_i values std::vector<Float> xvec; std::vector<Float> rvec; // vector of rate approximations // do the first iteration outside the while loop auto x1 = x0 - (f(x0) / derivative(f, x0)); xvec.push_back(x1); Float currtol = static_cast<Float>(std::abs(xvec[0] - x0)); // number of iterations : we have already performed one auto i = 1; Float rate = NAN; rvec.push_back(rate); Float x_iminus1; Float x_i; Float x_iplus1; Float deltaxp1; while (currtol > abstol) { x_iminus1 = xvec[i - 1]; x_i = x_iminus1 - (f(x_iminus1) / derivative(f, x_iminus1)); xvec.push_back(x_i); x_iplus1 = x_i - (f(x_i) / derivative(f, x_i)); currtol = std::abs(x_i - x_iminus1); deltaxp1 = std::abs(x_iplus1 - x_i); if ((i - 2) > 0) { rate = std::log(deltaxp1 / currtol) / std::log(currtol / std::abs(x_iminus1 - xvec[i - 2])); rvec.push_back(rate); } else { rvec.push_back(NAN); } ++i; } return std::make_tuple(xvec, i, rvec); } template<typename Func, typename Float> void test_newton_method(const Func& f, Float x0, Float abstol, const std::string& funcname = "f", const std::string& filename = "test_f.txt") { const int nameWidth = 24; const int numWidth = 25; std::ofstream file; file.open(filename.c_str(), std::ios::out | std::ios::app); file << std::scientific << std::setprecision(15); file << "Getting the roots of '" << funcname << "' given x_0 = " << x0 << " and abstol = " << abstol << std::endl; auto tuple = newton_method(f, x0, abstol); auto xvec = std::get<0>(tuple); auto iters = std::get<1>(tuple); auto rvec = std::get<2>(tuple); printElement("i", nameWidth, file); printElement("x_i", nameWidth, file); printElement("|x_i - x_{i - 1}|", nameWidth, file); printElement("rate", nameWidth, file); file << '\n'; for (auto i = 0; i < xvec.size(); ++i) { printElement(i, numWidth, file); printElement(xvec[i], numWidth, file); if ((i - 1) >= 0) { printElement(std::abs(xvec[i] - xvec[i - 1]), numWidth, file); } printElement(rvec[i], numWidth, file); file << '\n'; } file << "END" << std::endl; } namespace newton { // we can't use functors with the derivative function // so we have to stick to traditional functions double f1(double x) { return x * x - 3 * x + 2; } double f2(double x) { return x * x * x - 2 * x - 5; } double f3(double x) { return std::exp(-x) - x; } double f4(double x) { return std::sin(x) * x - 1; } double f5(double x) { return x * x * x - 3 * x * x + 3 * x - 1; } } void test_newton(double abstol) { using namespace newton; // for functions f1 to f5 std::vector<double (*)(double)> vec {f1, f2, f3, f4, f5}; std::vector<std::string> filenames {"f1.txt", "f2.txt", "f3.txt", "f4.txt", "f5.txt"}; std::vector<std::string> funcnames {"f1", "f2", "f3", "f4", "f5"}; std::vector<double> xnaughts {2.1, 2.5, 0.6, 0.9, 0.5}; for (auto i = 0; i < vec.size(); ++i) { test_newton_method(*vec[i], xnaughts[i], abstol, funcnames[i], filenames[i]); } } template<typename Func, typename Float> std::tuple<std::vector<Float>, int, std::vector<Float>> secant_method(const Func& f, Float x0, Float x1, Float abstol) { // vector to store intermediate x_i values std::vector<Float> xvec; std::vector<Float> rvec; // vector of rate approximations // do the first iteration outside the while loop xvec.push_back(x1); auto x2 = x1 - f(x1) * ((x1 - x0) / (f(x1) - f(x0))); xvec.push_back(x2); Float currtol = static_cast<Float>(std::abs(xvec[0] - x1)); // number of iterations : we have already performed one auto i = 2; Float rate = NAN; rvec.push_back(rate); Float x_iminus2; Float x_iminus1; Float x_i; Float x_iplus1; Float deltaxp1; while (currtol > abstol) { x_iminus2 = xvec[i - 2]; x_iminus1 = xvec[i - 1]; x_i = x_iminus1 - f(x_iminus1) * ((x_iminus1 - x_iminus2) / (f(x_iminus1) - f(x_iminus2))); xvec.push_back(x_i); x_iplus1 = x_i - f(x_i) * ((x_i - x_iminus1) / (f(x_i) - f(x_iminus1))); currtol = std::abs(x_i - x_iminus1); deltaxp1 = std::abs(x_iplus1 - x_i); if ((i - 2) > 0) { rate = std::log(deltaxp1 / currtol) / std::log(currtol / std::abs(x_iminus1 - xvec[i - 2])); rvec.push_back(rate); } else { rvec.push_back(NAN); } ++i; } return std::make_tuple(xvec, i, rvec); } template<typename Func, typename Float> void test_secant_method(const Func& f, Float x0, Float x1, Float abstol, const std::string& funcname = "f", const std::string& filename = "test_f.txt") { const int nameWidth = 24; const int numWidth = 25; std::ofstream file; file.open(filename.c_str(), std::ios::out | std::ios::app); file << std::scientific << std::setprecision(15); file << "Getting the roots of '" << funcname << "' given x_0 = " << x0 << ", x_1 = " << x1 << " and abstol = " << abstol << std::endl; auto tuple = secant_method(f, x0, x1, abstol); auto xvec = std::get<0>(tuple); auto iters = std::get<1>(tuple); auto rvec = std::get<2>(tuple); printElement("i", nameWidth, file); printElement("x_i", nameWidth, file); printElement("|x_i - x_{i - 1}|", nameWidth, file); printElement("rate", nameWidth, file); file << '\n'; for (auto i = 0; i < xvec.size(); ++i) { printElement(i, numWidth, file); printElement(xvec[i], numWidth, file); if ((i - 1) >= 0) { printElement(std::abs(xvec[i] - xvec[i - 1]), numWidth, file); } printElement(rvec[i], numWidth, file); file << '\n'; } file << "END" << std::endl; } template<typename Float, typename = std::enable_if<std::is_arithmetic<Float>::value>::type> Float midpoint(Float a, Float b) { return a + (b - a) / 2; } template<typename Float, typename = std::enable_if<std::is_arithmetic<Float>::value>::type> int sign(Float a) { return a > 0 ? 1 : -1; } template<typename Func, typename Float> Float bisection_method(const Func& f, Float a, Float b, Float abstol, int numiters) { auto n = 1; Float c; Float l = a; Float u = b; while (n <= numiters) { c = midpoint(l, u); if ((u - l) < abstol) { break; } if (sign(f(c)) == sign(f(l))) { l = c; } else { b = c; } n++; } return c; } }<|endoftext|>
<commit_before>#include "mapgeneratorwindow.h" #include "ui_mapgeneratorwindow.h" #include <QFileDialog> #include <QValidator> #include <JoshMath.h> MapGeneratorWindow::MapGeneratorWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MapGeneratorWindow) { ui->setupUi(this); } MapGeneratorWindow::~MapGeneratorWindow() { delete ui; } void MapGeneratorWindow::init() { // popupate the selectable input map combo box (this might be refactored out later) QStringList inputMapTypes; inputMapTypes.push_back("Diffuse Map"); inputMapTypes.push_back("Height Map"); ui->comboBox_inputMapType->addItems(inputMapTypes); ui->comboBox_inputMapType->setCurrentIndex(0); QStringList outputMapTypes; outputMapTypes.push_back("Normal Map"); outputMapTypes.push_back("Edge Map"); ui->comboBox_->addItems(outputMapTypes); ui->comboBox_->setCurrentIndex(1); // connect ui object to correct methods connect(ui->actionSet_Input_Map, &QAction::triggered, this, &MapGeneratorWindow::onOpenMap); connect(ui->pushButton_generateMap, &QPushButton::pressed, this, &MapGeneratorWindow::onGenerateMapButtonPressed); connect(ui->actionSave_Output_Map, &QAction::triggered, this, &MapGeneratorWindow::onSaveOutputMap); // disable the generate button (gets re enabled once an input map is provided) ui->pushButton_generateMap->setDisabled(true); // add QValidator objects for the ui->lineEdit_bumpAmp->setValidator(new QDoubleValidator()); ui->lineEdit_edgeMapSensivity->setValidator(new QIntValidator(0, 255 * 3)); } void MapGeneratorWindow::onOpenMap() { // just deal with image files QString inputFileName = QFileDialog::getOpenFileName(this, tr("Select an Image file"), QString(""), tr("Image files (*.bmp;*.jpg;*.png)")); if (inputFileName == QString()) { // no file has been selected return; } QPixmap imagePixelMap(inputFileName); ui->label_inputMap->setPixmap(imagePixelMap); // enable the generate button ui->pushButton_generateMap->setDisabled(false); } void MapGeneratorWindow::onSaveOutputMap() { // make sure that theres a map to save, if not return const QPixmap * outputImage = ui->label_outputMap->pixmap(); if (outputImage) { QString saveFileStr = QFileDialog::getSaveFileName(this, tr("Save output"), "", tr("Images (*.png)")); if (saveFileStr != QString()) { // save the file outputImage->save(saveFileStr, "png"); } } } void MapGeneratorWindow::onGenerateMapButtonPressed() { /* 1. check the input and output combo boxes are for the correct map type 2. check that the map generation controls aren't values that will crash the program 3. once validation has been passed call the correct generation method */ if (!validateInputs()) { return; } // clear the output label pixel map QPixmap defaultMap(10, 10); ui->label_outputMap->setPixmap(defaultMap); if (ui->comboBox_->currentText().toStdString() == "Normal Map") { float ampVal = 1.0f; if (ui->lineEdit_bumpAmp->text().toStdString() != "") { ampVal = ui->lineEdit_bumpAmp->text().toFloat(); } generateNormalMap(ampVal); } else if (ui->comboBox_->currentText().toStdString() == "Edge Map") { int sensitivityVal = 50; if (ui->lineEdit_edgeMapSensivity->text().toStdString() != "") { sensitivityVal = ui->lineEdit_edgeMapSensivity->text().toInt(); } generateEdgeMap(sensitivityVal); } } bool MapGeneratorWindow::validateInputs() { if (!validateInputMapCorrectForOutput()) { return false; } // add additional validation here if needed return true; } bool MapGeneratorWindow::validateInputMapCorrectForOutput() { // if diffuse map, then edge map // if height map, then normal map if (ui->comboBox_inputMapType->currentText().toStdString() == "Diffuse Map") { if (ui->comboBox_->currentText().toStdString() == "Edge Map") { return true; } } else if (ui->comboBox_inputMapType->currentText().toStdString() == "Height Map") { if (ui->comboBox_->currentText().toStdString() == "Normal Map") { return true; } else if (ui->comboBox_->currentText().toStdString() == "Edge Map") { return true; } } return false; } void MapGeneratorWindow::generateEdgeMap(int sensitivity) { // clear the current output map ui->label_outputMap->clear(); const QPixmap * inputPixelMap = ui->label_inputMap->pixmap(); const QImage originalImage = inputPixelMap->toImage(); QImage generatedMap(originalImage); int originalImageWidth = originalImage.width(), originalImageHeight = originalImage.height(); QRgb primaryColour = qRgb(0, 0, 0); QRgb edgeColour = qRgb(255, 255, 255); for (size_t i = 0; i < originalImageWidth; ++i) { for (size_t j = 0; j < originalImageHeight; ++j) { generatedMap.setPixelColor(i, j, primaryColour); } } // refactor to use the matrix approach later // now run the edge detection step // vertical scan for (int x = 0; x < originalImageWidth; ++x) { for (int y = 1; y < originalImageHeight; ++y) { // if it's an edge set the pixel to the edge colour const QRgb lastPx = originalImage.pixel(x, y - 1); const QRgb currentPx = originalImage.pixel(x, y); int diff = difference(lastPx, currentPx); if (diff > sensitivity) { generatedMap.setPixelColor(x, y, edgeColour); } } } // horisontal scan for (int y = 0; y < originalImageHeight; ++y) { for (int x = 1; x < originalImageWidth; ++x) { // if it's an edge set the pixel to the edge colour const QRgb lastPx = originalImage.pixel(x - 1, y); const QRgb currentPx = originalImage.pixel(x, y); int diff = difference(lastPx, currentPx); if (diff > sensitivity) { generatedMap.setPixelColor(x, y, edgeColour); } } } QPixmap outputPixelMap = QPixmap::fromImage(generatedMap); ui->label_outputMap->setPixmap(outputPixelMap); } void MapGeneratorWindow::generateNormalMap(float amplertude) { const QPixmap * inputPixelMap = ui->label_inputMap->pixmap(); const QImage originalImage = inputPixelMap->toImage(); QImage generatedMap(originalImage); int originalImageWidth = originalImage.width(), originalImageHeight = originalImage.height(); int halfWayWidth = originalImageWidth / 2; int halfWayHeight = originalImageHeight / 2; QRgb primaryColour = qRgb(0, 0, 0); QRgb secondaryColour = qRgb(255, 255, 255); for (size_t i = 0; i < originalImageWidth; ++i) { for (size_t j = 0; j < originalImageHeight; ++j) { bool pastHalfWayPointX = i > halfWayWidth; bool pastHalfWayPointY = j > halfWayHeight; bool usePrimaryColour = pastHalfWayPointX ^ pastHalfWayPointY; if (usePrimaryColour) { generatedMap.setPixelColor(i, j, primaryColour); } else { generatedMap.setPixelColor(i, j, secondaryColour); } } } QPixmap outputPixelMap = QPixmap::fromImage(generatedMap); ui->label_outputMap->setPixmap(outputPixelMap); } inline unsigned int MapGeneratorWindow::difference(const QRgb a, const QRgb b) { int aRed = qRed(a); int aGreen = qGreen(a); int aBlue = qBlue(a); int bRed = qRed(b); int bGreen = qGreen(b); int bBlue = qBlue(b); int diff = 0; diff += abs(aRed - bRed); diff += abs(aGreen - bGreen); diff += abs(aBlue- bBlue); return diff; }<commit_msg>Partial progress in normal map generator<commit_after>#include "mapgeneratorwindow.h" #include "ui_mapgeneratorwindow.h" #include <QFileDialog> #include <QValidator> #include <JoshMath.h> MapGeneratorWindow::MapGeneratorWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MapGeneratorWindow) { ui->setupUi(this); } MapGeneratorWindow::~MapGeneratorWindow() { delete ui; } void MapGeneratorWindow::init() { // popupate the selectable input map combo box (this might be refactored out later) QStringList inputMapTypes; inputMapTypes.push_back("Diffuse Map"); inputMapTypes.push_back("Height Map"); ui->comboBox_inputMapType->addItems(inputMapTypes); ui->comboBox_inputMapType->setCurrentIndex(0); QStringList outputMapTypes; outputMapTypes.push_back("Normal Map"); outputMapTypes.push_back("Edge Map"); ui->comboBox_->addItems(outputMapTypes); ui->comboBox_->setCurrentIndex(1); // connect ui object to correct methods connect(ui->actionSet_Input_Map, &QAction::triggered, this, &MapGeneratorWindow::onOpenMap); connect(ui->pushButton_generateMap, &QPushButton::pressed, this, &MapGeneratorWindow::onGenerateMapButtonPressed); connect(ui->actionSave_Output_Map, &QAction::triggered, this, &MapGeneratorWindow::onSaveOutputMap); // disable the generate button (gets re enabled once an input map is provided) ui->pushButton_generateMap->setDisabled(true); // add QValidator objects for the ui->lineEdit_bumpAmp->setValidator(new QDoubleValidator()); ui->lineEdit_edgeMapSensivity->setValidator(new QIntValidator(0, 255 * 3)); } void MapGeneratorWindow::onOpenMap() { // just deal with image files QString inputFileName = QFileDialog::getOpenFileName(this, tr("Select an Image file"), QString(""), tr("Image files (*.bmp;*.jpg;*.png)")); if (inputFileName == QString()) { // no file has been selected return; } QPixmap imagePixelMap(inputFileName); ui->label_inputMap->setPixmap(imagePixelMap); // enable the generate button ui->pushButton_generateMap->setDisabled(false); } void MapGeneratorWindow::onSaveOutputMap() { // make sure that theres a map to save, if not return const QPixmap * outputImage = ui->label_outputMap->pixmap(); if (outputImage) { QString saveFileStr = QFileDialog::getSaveFileName(this, tr("Save output"), "", tr("Images (*.png)")); if (saveFileStr != QString()) { // save the file outputImage->save(saveFileStr, "png"); } } } void MapGeneratorWindow::onGenerateMapButtonPressed() { /* 1. check the input and output combo boxes are for the correct map type 2. check that the map generation controls aren't values that will crash the program 3. once validation has been passed call the correct generation method */ if (!validateInputs()) { return; } // clear the output label pixel map QPixmap defaultMap(10, 10); ui->label_outputMap->setPixmap(defaultMap); if (ui->comboBox_->currentText().toStdString() == "Normal Map") { float ampVal = 1.0f; if (ui->lineEdit_bumpAmp->text().toStdString() != "") { ampVal = ui->lineEdit_bumpAmp->text().toFloat(); } generateNormalMap(ampVal); } else if (ui->comboBox_->currentText().toStdString() == "Edge Map") { int sensitivityVal = 50; if (ui->lineEdit_edgeMapSensivity->text().toStdString() != "") { sensitivityVal = ui->lineEdit_edgeMapSensivity->text().toInt(); } generateEdgeMap(sensitivityVal); } } bool MapGeneratorWindow::validateInputs() { if (!validateInputMapCorrectForOutput()) { return false; } // add additional validation here if needed return true; } bool MapGeneratorWindow::validateInputMapCorrectForOutput() { // if diffuse map, then edge map // if height map, then normal map if (ui->comboBox_inputMapType->currentText().toStdString() == "Diffuse Map") { if (ui->comboBox_->currentText().toStdString() == "Edge Map") { return true; } } else if (ui->comboBox_inputMapType->currentText().toStdString() == "Height Map") { if (ui->comboBox_->currentText().toStdString() == "Normal Map") { return true; } else if (ui->comboBox_->currentText().toStdString() == "Edge Map") { return true; } } return false; } void MapGeneratorWindow::generateEdgeMap(int sensitivity) { // clear the current output map ui->label_outputMap->clear(); const QPixmap * inputPixelMap = ui->label_inputMap->pixmap(); const QImage originalImage = inputPixelMap->toImage(); QImage generatedMap(originalImage); int originalImageWidth = originalImage.width(), originalImageHeight = originalImage.height(); QRgb primaryColour = qRgb(0, 0, 0); QRgb edgeColour = qRgb(255, 255, 255); for (size_t i = 0; i < originalImageWidth; ++i) { for (size_t j = 0; j < originalImageHeight; ++j) { generatedMap.setPixelColor(i, j, primaryColour); } } // refactor to use the matrix approach later // now run the edge detection step // vertical scan for (int x = 0; x < originalImageWidth; ++x) { for (int y = 1; y < originalImageHeight; ++y) { // if it's an edge set the pixel to the edge colour const QRgb lastPx = originalImage.pixel(x, y - 1); const QRgb currentPx = originalImage.pixel(x, y); int diff = difference(lastPx, currentPx); if (diff > sensitivity) { generatedMap.setPixelColor(x, y, edgeColour); } } } // horisontal scan for (int y = 0; y < originalImageHeight; ++y) { for (int x = 1; x < originalImageWidth; ++x) { // if it's an edge set the pixel to the edge colour const QRgb lastPx = originalImage.pixel(x - 1, y); const QRgb currentPx = originalImage.pixel(x, y); int diff = difference(lastPx, currentPx); if (diff > sensitivity) { generatedMap.setPixelColor(x, y, edgeColour); } } } QPixmap outputPixelMap = QPixmap::fromImage(generatedMap); ui->label_outputMap->setPixmap(outputPixelMap); } void MapGeneratorWindow::generateNormalMap(float amplertude) { const QPixmap * inputPixelMap = ui->label_inputMap->pixmap(); const QImage originalImage = inputPixelMap->toImage(); QImage generatedMap(originalImage); int originalImageWidth = originalImage.width(), originalImageHeight = originalImage.height(); const float imageAspectRatio = (float)originalImageWidth / (float)originalImageHeight; float heightPxLeftOfCurrent = 0.0f; float heightPxRightOfCurrent = 0.0f; float heightPxUpOfCurrent = 0.0f; float heightPxDownOfCurrent = 0.0f; for (int pxPosX = 0; pxPosX < originalImageWidth; ++pxPosX) { for (int pxPosY = 0; pxPosY < originalImageHeight; ++pxPosY) { // 0 everything, the edges will assume 0.0 float heightPxLeftOfCurrent = 0.0f; float heightPxRightOfCurrent = 0.0f; float heightPxUpOfCurrent = 0.0f; float heightPxDownOfCurrent = 0.0f; // pick up here from the first commit dev branch, main.cpp, generateBumpMap(), ln 129 + } } QPixmap outputPixelMap = QPixmap::fromImage(generatedMap); ui->label_outputMap->setPixmap(outputPixelMap); } inline unsigned int MapGeneratorWindow::difference(const QRgb a, const QRgb b) { int aRed = qRed(a); int aGreen = qGreen(a); int aBlue = qBlue(a); int bRed = qRed(b); int bGreen = qGreen(b); int bBlue = qBlue(b); int diff = 0; diff += abs(aRed - bRed); diff += abs(aGreen - bGreen); diff += abs(aBlue- bBlue); return diff; }<|endoftext|>
<commit_before>/**************************************************************************** * Copyright 2016 BlueMasters * * 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 <Arduino.h> #include "Solenoid.h" #include "App.h" // Give time for the disk to fall out of the RFID sensor field #define SOLENOID_WAITING_TIME 1000 // msec void Solenoid::begin() { off(); pinMode(_impulsePin, OUTPUT); _state = SOLENOID_IDLE; _sensorState = NO_CARD; } void Solenoid::on() { digitalWrite(_impulsePin, LOW); _sensorState = NO_CARD; // see in tick to find out why this is here. } void Solenoid::off() { digitalWrite(_impulsePin, HIGH); } void Solenoid::fire(long t) { _timestamp = t; on(); } void Solenoid::release(long t) { _timestamp = t; off(); _led.off(); } void Solenoid::tick() { long now = millis(); // Read sensor state enum rfidSensorStatus newSensorState = _sensor.rfidSensorStatus(); // If we have a card, so we save this in the _sensorState attribute. // We will receive this information only once, and it might arrive // during a "FROZEN" state, so we have to save it. We will put it // back to NO_CARD only when we pull the solenoid. if (newSensorState == VALID_CARD || newSensorState == INVALID_CARD) { _sensorState = newSensorState; } switch (_state) { case SOLENOID_IDLE: if (app.emergency) { fire(now); _state = SOLENOID_FIRED; _led.green(); } else if (_sensorState == VALID_CARD) { _led.green(); _timestamp = now; _state = SOLENOID_FROZEN; } else if (_sensorState == INVALID_CARD) { _led.red(); _timestamp = now; _state = SOLENOID_FROZEN; } else { // Idle and no reason to change. off(); _led.off(); } break; case SOLENOID_FROZEN: if (now - _timestamp > app.DF) { fire(now); _state = SOLENOID_FIRED; // I decided to not clear the LED here. It will stay // a little bit longer and will be cleared in the next state. } break; case SOLENOID_FIRED: if (now - _timestamp > app.DI) { release(now); _state = SOLENOID_WAITING; } break; case SOLENOID_WAITING: if (now - _timestamp > SOLENOID_WAITING_TIME) { _state = SOLENOID_IDLE; } break; default: { _state = SOLENOID_IDLE; break; } } }; int Solenoid::selfCheck0() { _led.red(); on(); delay(200); return 0; } int Solenoid::selfCheck1() { _led.green(); off(); delay(200); return 0; } int Solenoid::selfCheck2() { _led.off(); return 0; } <commit_msg>Change: improve RFID - Solenoid interaction<commit_after>/**************************************************************************** * Copyright 2016 BlueMasters * * 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 <Arduino.h> #include "Solenoid.h" #include "App.h" // Give time for the disk to fall out of the RFID sensor field #define SOLENOID_WAITING_TIME 1000 // msec void Solenoid::begin() { off(); pinMode(_impulsePin, OUTPUT); _state = SOLENOID_IDLE; _sensorState = NO_CARD; } void Solenoid::on() { digitalWrite(_impulsePin, LOW); } void Solenoid::off() { digitalWrite(_impulsePin, HIGH); } void Solenoid::fire(long t) { _timestamp = t; on(); } void Solenoid::release(long t) { _timestamp = t; off(); _led.off(); } void Solenoid::tick() { long now = millis(); // Read sensor state enum rfidSensorStatus newSensorState = _sensor.rfidSensorStatus(); // If we have a card, so we save this in the _sensorState attribute. // We will receive this information only once, and it might arrive // during a "FROZEN" state, so we have to save it. if (newSensorState == VALID_CARD || newSensorState == INVALID_CARD) { _sensorState = newSensorState; } switch (_state) { case SOLENOID_IDLE: if (app.emergency) { fire(now); _state = SOLENOID_FIRED; _led.green(); } else if (_sensorState == VALID_CARD) { _led.green(); _timestamp = now; _state = SOLENOID_FROZEN; _sensorState = NO_CARD; } else if (_sensorState == INVALID_CARD) { _led.red(); _timestamp = now; _state = SOLENOID_FROZEN; _sensorState = NO_CARD; } else { // Idle and no reason to change. off(); _led.off(); } break; case SOLENOID_FROZEN: if (now - _timestamp > app.DF) { fire(now); _state = SOLENOID_FIRED; // I decided to not clear the LED here. It will stay // a little bit longer and will be cleared in the next state. } break; case SOLENOID_FIRED: if (now - _timestamp > app.DI) { release(now); _state = SOLENOID_WAITING; } break; case SOLENOID_WAITING: if (now - _timestamp > SOLENOID_WAITING_TIME) { _state = SOLENOID_IDLE; } break; default: { _state = SOLENOID_IDLE; break; } } }; int Solenoid::selfCheck0() { _led.red(); on(); delay(200); return 0; } int Solenoid::selfCheck1() { _led.green(); off(); delay(200); return 0; } int Solenoid::selfCheck2() { _led.off(); return 0; } <|endoftext|>
<commit_before>//===--- StringMap.cpp - String Hash table map implementation -------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Chris Lattner and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the StringMap class. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringMap.h" #include <cassert> using namespace llvm; StringMapImpl::StringMapImpl(unsigned InitSize, unsigned itemSize) { ItemSize = itemSize; // If a size is specified, initialize the table with that many buckets. if (InitSize) { init(InitSize); return; } // Otherwise, initialize it with zero buckets to avoid the allocation. TheTable = 0; NumBuckets = 0; NumItems = 0; NumTombstones = 0; } void StringMapImpl::init(unsigned InitSize) { assert((InitSize & (InitSize-1)) == 0 && "Init Size must be a power of 2 or zero!"); NumBuckets = InitSize ? InitSize : 16; NumItems = 0; NumTombstones = 0; TheTable = (ItemBucket*)calloc(NumBuckets+1, sizeof(ItemBucket)); // Allocate one extra bucket, set it to look filled so the iterators stop at // end. TheTable[NumBuckets].Item = (StringMapEntryBase*)2; } /// HashString - Compute a hash code for the specified string. /// static unsigned HashString(const char *Start, const char *End) { // Bernstein hash function. unsigned int Result = 0; // TODO: investigate whether a modified bernstein hash function performs // better: http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx // X*33+c -> X*33^c while (Start != End) Result = Result * 33 + *Start++; Result = Result + (Result >> 5); return Result; } /// LookupBucketFor - Look up the bucket that the specified string should end /// up in. If it already exists as a key in the map, the Item pointer for the /// specified bucket will be non-null. Otherwise, it will be null. In either /// case, the FullHashValue field of the bucket will be set to the hash value /// of the string. unsigned StringMapImpl::LookupBucketFor(const char *NameStart, const char *NameEnd) { unsigned HTSize = NumBuckets; if (HTSize == 0) { // Hash table unallocated so far? init(16); HTSize = NumBuckets; } unsigned FullHashValue = HashString(NameStart, NameEnd); unsigned BucketNo = FullHashValue & (HTSize-1); unsigned ProbeAmt = 1; int FirstTombstone = -1; while (1) { ItemBucket &Bucket = TheTable[BucketNo]; StringMapEntryBase *BucketItem = Bucket.Item; // If we found an empty bucket, this key isn't in the table yet, return it. if (BucketItem == 0) { // If we found a tombstone, we want to reuse the tombstone instead of an // empty bucket. This reduces probing. if (FirstTombstone != -1) { TheTable[FirstTombstone].FullHashValue = FullHashValue; return FirstTombstone; } Bucket.FullHashValue = FullHashValue; return BucketNo; } if (BucketItem == getTombstoneVal()) { // Skip over tombstones. However, remember the first one we see. if (FirstTombstone == -1) FirstTombstone = BucketNo; } else if (Bucket.FullHashValue == FullHashValue) { // If the full hash value matches, check deeply for a match. The common // case here is that we are only looking at the buckets (for item info // being non-null and for the full hash value) not at the items. This // is important for cache locality. // Do the comparison like this because NameStart isn't necessarily // null-terminated! char *ItemStr = (char*)BucketItem+ItemSize; unsigned ItemStrLen = BucketItem->getKeyLength(); if (unsigned(NameEnd-NameStart) == ItemStrLen && memcmp(ItemStr, NameStart, ItemStrLen) == 0) { // We found a match! return BucketNo; } } // Okay, we didn't find the item. Probe to the next bucket. BucketNo = (BucketNo+ProbeAmt) & (HTSize-1); // Use quadratic probing, it has fewer clumping artifacts than linear // probing and has good cache behavior in the common case. ++ProbeAmt; } } /// FindKey - Look up the bucket that contains the specified key. If it exists /// in the map, return the bucket number of the key. Otherwise return -1. /// This does not modify the map. int StringMapImpl::FindKey(const char *KeyStart, const char *KeyEnd) const { unsigned HTSize = NumBuckets; if (HTSize == 0) return -1; // Really empty table? unsigned FullHashValue = HashString(KeyStart, KeyEnd); unsigned BucketNo = FullHashValue & (HTSize-1); unsigned ProbeAmt = 1; while (1) { ItemBucket &Bucket = TheTable[BucketNo]; StringMapEntryBase *BucketItem = Bucket.Item; // If we found an empty bucket, this key isn't in the table yet, return. if (BucketItem == 0) return -1; if (BucketItem == getTombstoneVal()) { // Ignore tombstones. } else if (Bucket.FullHashValue == FullHashValue) { // If the full hash value matches, check deeply for a match. The common // case here is that we are only looking at the buckets (for item info // being non-null and for the full hash value) not at the items. This // is important for cache locality. // Do the comparison like this because NameStart isn't necessarily // null-terminated! char *ItemStr = (char*)BucketItem+ItemSize; unsigned ItemStrLen = BucketItem->getKeyLength(); if (unsigned(KeyEnd-KeyStart) == ItemStrLen && memcmp(ItemStr, KeyStart, ItemStrLen) == 0) { // We found a match! return BucketNo; } } // Okay, we didn't find the item. Probe to the next bucket. BucketNo = (BucketNo+ProbeAmt) & (HTSize-1); // Use quadratic probing, it has fewer clumping artifacts than linear // probing and has good cache behavior in the common case. ++ProbeAmt; } } /// RemoveKey - Remove the specified StringMapEntry from the table, but do not /// delete it. This aborts if the value isn't in the table. void StringMapImpl::RemoveKey(StringMapEntryBase *V) { const char *VStr = (char*)V + ItemSize; StringMapEntryBase *V2 = RemoveKey(VStr, VStr+V->getKeyLength()); V2 = V2; assert(V == V2 && "Didn't find key?"); } /// RemoveKey - Remove the StringMapEntry for the specified key from the /// table, returning it. If the key is not in the table, this returns null. StringMapEntryBase *StringMapImpl::RemoveKey(const char *KeyStart, const char *KeyEnd) { int Bucket = FindKey(KeyStart, KeyEnd); if (Bucket == -1) return 0; StringMapEntryBase *Result = TheTable[Bucket].Item; TheTable[Bucket].Item = getTombstoneVal(); --NumItems; ++NumTombstones; return Result; } /// RehashTable - Grow the table, redistributing values into the buckets with /// the appropriate mod-of-hashtable-size. void StringMapImpl::RehashTable() { unsigned NewSize = NumBuckets*2; // Allocate one extra bucket which will always be non-empty. This allows the // iterators to stop at end. ItemBucket *NewTableArray =(ItemBucket*)calloc(NewSize+1, sizeof(ItemBucket)); NewTableArray[NewSize].Item = (StringMapEntryBase*)2; // Rehash all the items into their new buckets. Luckily :) we already have // the hash values available, so we don't have to rehash any strings. for (ItemBucket *IB = TheTable, *E = TheTable+NumBuckets; IB != E; ++IB) { if (IB->Item && IB->Item != getTombstoneVal()) { // Fast case, bucket available. unsigned FullHash = IB->FullHashValue; unsigned NewBucket = FullHash & (NewSize-1); if (NewTableArray[NewBucket].Item == 0) { NewTableArray[FullHash & (NewSize-1)].Item = IB->Item; NewTableArray[FullHash & (NewSize-1)].FullHashValue = FullHash; continue; } // Otherwise probe for a spot. unsigned ProbeSize = 1; do { NewBucket = (NewBucket + ProbeSize++) & (NewSize-1); } while (NewTableArray[NewBucket].Item); // Finally found a slot. Fill it in. NewTableArray[NewBucket].Item = IB->Item; NewTableArray[NewBucket].FullHashValue = FullHash; } } delete[] TheTable; TheTable = NewTableArray; NumBuckets = NewSize; } <commit_msg>stringmap memory managed with malloc now<commit_after>//===--- StringMap.cpp - String Hash table map implementation -------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Chris Lattner and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the StringMap class. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringMap.h" #include <cassert> using namespace llvm; StringMapImpl::StringMapImpl(unsigned InitSize, unsigned itemSize) { ItemSize = itemSize; // If a size is specified, initialize the table with that many buckets. if (InitSize) { init(InitSize); return; } // Otherwise, initialize it with zero buckets to avoid the allocation. TheTable = 0; NumBuckets = 0; NumItems = 0; NumTombstones = 0; } void StringMapImpl::init(unsigned InitSize) { assert((InitSize & (InitSize-1)) == 0 && "Init Size must be a power of 2 or zero!"); NumBuckets = InitSize ? InitSize : 16; NumItems = 0; NumTombstones = 0; TheTable = (ItemBucket*)calloc(NumBuckets+1, sizeof(ItemBucket)); // Allocate one extra bucket, set it to look filled so the iterators stop at // end. TheTable[NumBuckets].Item = (StringMapEntryBase*)2; } /// HashString - Compute a hash code for the specified string. /// static unsigned HashString(const char *Start, const char *End) { // Bernstein hash function. unsigned int Result = 0; // TODO: investigate whether a modified bernstein hash function performs // better: http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx // X*33+c -> X*33^c while (Start != End) Result = Result * 33 + *Start++; Result = Result + (Result >> 5); return Result; } /// LookupBucketFor - Look up the bucket that the specified string should end /// up in. If it already exists as a key in the map, the Item pointer for the /// specified bucket will be non-null. Otherwise, it will be null. In either /// case, the FullHashValue field of the bucket will be set to the hash value /// of the string. unsigned StringMapImpl::LookupBucketFor(const char *NameStart, const char *NameEnd) { unsigned HTSize = NumBuckets; if (HTSize == 0) { // Hash table unallocated so far? init(16); HTSize = NumBuckets; } unsigned FullHashValue = HashString(NameStart, NameEnd); unsigned BucketNo = FullHashValue & (HTSize-1); unsigned ProbeAmt = 1; int FirstTombstone = -1; while (1) { ItemBucket &Bucket = TheTable[BucketNo]; StringMapEntryBase *BucketItem = Bucket.Item; // If we found an empty bucket, this key isn't in the table yet, return it. if (BucketItem == 0) { // If we found a tombstone, we want to reuse the tombstone instead of an // empty bucket. This reduces probing. if (FirstTombstone != -1) { TheTable[FirstTombstone].FullHashValue = FullHashValue; return FirstTombstone; } Bucket.FullHashValue = FullHashValue; return BucketNo; } if (BucketItem == getTombstoneVal()) { // Skip over tombstones. However, remember the first one we see. if (FirstTombstone == -1) FirstTombstone = BucketNo; } else if (Bucket.FullHashValue == FullHashValue) { // If the full hash value matches, check deeply for a match. The common // case here is that we are only looking at the buckets (for item info // being non-null and for the full hash value) not at the items. This // is important for cache locality. // Do the comparison like this because NameStart isn't necessarily // null-terminated! char *ItemStr = (char*)BucketItem+ItemSize; unsigned ItemStrLen = BucketItem->getKeyLength(); if (unsigned(NameEnd-NameStart) == ItemStrLen && memcmp(ItemStr, NameStart, ItemStrLen) == 0) { // We found a match! return BucketNo; } } // Okay, we didn't find the item. Probe to the next bucket. BucketNo = (BucketNo+ProbeAmt) & (HTSize-1); // Use quadratic probing, it has fewer clumping artifacts than linear // probing and has good cache behavior in the common case. ++ProbeAmt; } } /// FindKey - Look up the bucket that contains the specified key. If it exists /// in the map, return the bucket number of the key. Otherwise return -1. /// This does not modify the map. int StringMapImpl::FindKey(const char *KeyStart, const char *KeyEnd) const { unsigned HTSize = NumBuckets; if (HTSize == 0) return -1; // Really empty table? unsigned FullHashValue = HashString(KeyStart, KeyEnd); unsigned BucketNo = FullHashValue & (HTSize-1); unsigned ProbeAmt = 1; while (1) { ItemBucket &Bucket = TheTable[BucketNo]; StringMapEntryBase *BucketItem = Bucket.Item; // If we found an empty bucket, this key isn't in the table yet, return. if (BucketItem == 0) return -1; if (BucketItem == getTombstoneVal()) { // Ignore tombstones. } else if (Bucket.FullHashValue == FullHashValue) { // If the full hash value matches, check deeply for a match. The common // case here is that we are only looking at the buckets (for item info // being non-null and for the full hash value) not at the items. This // is important for cache locality. // Do the comparison like this because NameStart isn't necessarily // null-terminated! char *ItemStr = (char*)BucketItem+ItemSize; unsigned ItemStrLen = BucketItem->getKeyLength(); if (unsigned(KeyEnd-KeyStart) == ItemStrLen && memcmp(ItemStr, KeyStart, ItemStrLen) == 0) { // We found a match! return BucketNo; } } // Okay, we didn't find the item. Probe to the next bucket. BucketNo = (BucketNo+ProbeAmt) & (HTSize-1); // Use quadratic probing, it has fewer clumping artifacts than linear // probing and has good cache behavior in the common case. ++ProbeAmt; } } /// RemoveKey - Remove the specified StringMapEntry from the table, but do not /// delete it. This aborts if the value isn't in the table. void StringMapImpl::RemoveKey(StringMapEntryBase *V) { const char *VStr = (char*)V + ItemSize; StringMapEntryBase *V2 = RemoveKey(VStr, VStr+V->getKeyLength()); V2 = V2; assert(V == V2 && "Didn't find key?"); } /// RemoveKey - Remove the StringMapEntry for the specified key from the /// table, returning it. If the key is not in the table, this returns null. StringMapEntryBase *StringMapImpl::RemoveKey(const char *KeyStart, const char *KeyEnd) { int Bucket = FindKey(KeyStart, KeyEnd); if (Bucket == -1) return 0; StringMapEntryBase *Result = TheTable[Bucket].Item; TheTable[Bucket].Item = getTombstoneVal(); --NumItems; ++NumTombstones; return Result; } /// RehashTable - Grow the table, redistributing values into the buckets with /// the appropriate mod-of-hashtable-size. void StringMapImpl::RehashTable() { unsigned NewSize = NumBuckets*2; // Allocate one extra bucket which will always be non-empty. This allows the // iterators to stop at end. ItemBucket *NewTableArray =(ItemBucket*)calloc(NewSize+1, sizeof(ItemBucket)); NewTableArray[NewSize].Item = (StringMapEntryBase*)2; // Rehash all the items into their new buckets. Luckily :) we already have // the hash values available, so we don't have to rehash any strings. for (ItemBucket *IB = TheTable, *E = TheTable+NumBuckets; IB != E; ++IB) { if (IB->Item && IB->Item != getTombstoneVal()) { // Fast case, bucket available. unsigned FullHash = IB->FullHashValue; unsigned NewBucket = FullHash & (NewSize-1); if (NewTableArray[NewBucket].Item == 0) { NewTableArray[FullHash & (NewSize-1)].Item = IB->Item; NewTableArray[FullHash & (NewSize-1)].FullHashValue = FullHash; continue; } // Otherwise probe for a spot. unsigned ProbeSize = 1; do { NewBucket = (NewBucket + ProbeSize++) & (NewSize-1); } while (NewTableArray[NewBucket].Item); // Finally found a slot. Fill it in. NewTableArray[NewBucket].Item = IB->Item; NewTableArray[NewBucket].FullHashValue = FullHash; } } free(TheTable); TheTable = NewTableArray; NumBuckets = NewSize; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: localfilehelper.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-16 15:11:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_configmgr.hxx" #ifndef CONFIGMGR_LOCALBE_LOCALFILEHELPER_HXX_ #include "localfilehelper.hxx" #endif #ifndef _CONFIGMGR_FILEHELPER_HXX_ #include "filehelper.hxx" #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif // _RTL_USTRBUF_HXX_ #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif #include <vector> namespace configmgr { namespace localbe { //------------------------------------------------------------------------------ bool isValidFileURL (rtl::OUString const& _sFileURL) { using osl::File; rtl::OUString sSystemPath; return _sFileURL.getLength() && (File::E_None == File::getSystemPathFromFileURL(_sFileURL, sSystemPath)); } //------------------------------------------------------------------------------ void validateFileURL(const rtl::OUString& _sFileURL, const uno::Reference<uno::XInterface>& pContext) throw(css::configuration::InvalidBootstrapFileException) { if (!isValidFileURL( _sFileURL)) { rtl::OUStringBuffer sMsg; sMsg.appendAscii(" Not a Valid File URL: \""); sMsg.append(_sFileURL); sMsg.appendAscii("\""); throw com::sun::star::configuration::InvalidBootstrapFileException( sMsg.makeStringAndClear(),pContext, rtl::OUString() ) ; } } //------------------------------------------------------------------------------ void checkFileExists(const rtl::OUString& _sFileURL,const uno::Reference<uno::XInterface>& pContext) throw (backend::CannotConnectException) { if (!FileHelper::fileExists(_sFileURL)) { rtl::OUStringBuffer sMsg; sMsg.appendAscii(" No Such File or Directory: \""); sMsg.append(_sFileURL); sMsg.appendAscii("\""); throw backend::CannotConnectException(sMsg.makeStringAndClear(), pContext, uno::Any()) ; } } //------------------------------------------------------------------------------ void checkIfDirectory(const rtl::OUString& _sFileURL, const uno::Reference<uno::XInterface>& pContext) throw (backend::BackendSetupException) { if (!FileHelper::dirExists(_sFileURL)) { rtl::OUStringBuffer sMsg; sMsg.appendAscii(" File:\""); sMsg.append(_sFileURL); sMsg.appendAscii("\" Must be a Directory\""); throw backend::BackendSetupException(sMsg.makeStringAndClear(),pContext, uno::Any()) ; } } // --------------------------------------------------------------------------------------- bool implEnsureAbsoluteURL(rtl::OUString & _rsURL) // also strips embedded dots etc. { using osl::File; rtl::OUString sBasePath = _rsURL; OSL_VERIFY(osl_Process_E_None == osl_getProcessWorkingDir(&sBasePath.pData)); rtl::OUString sAbsolute; if ( File::E_None == File::getAbsoluteFileURL(sBasePath, _rsURL, sAbsolute)) { _rsURL = sAbsolute; return true; } else { OSL_ENSURE(false, "Could not get absolute file URL for valid URL"); return false; } } // --------------------------------------------------------------------------------------- osl::DirectoryItem::RC implNormalizeURL(rtl::OUString & _sURL, osl::DirectoryItem& aDirItem) { using namespace osl; OSL_PRECOND(aDirItem.is(), "Opened DirItem required"); static const sal_uInt32 cFileStatusMask = FileStatusMask_FileURL; FileStatus aFileStatus(cFileStatusMask); DirectoryItem::RC rc = aDirItem.getFileStatus(aFileStatus); if (rc == DirectoryItem::E_None) { rtl::OUString aNormalizedURL = aFileStatus.getFileURL(); if (aNormalizedURL.getLength() != 0) _sURL = aNormalizedURL; else rc = DirectoryItem::E_INVAL; } return rc; } // --------------------------------------------------------------------------------------- bool normalizeURL(rtl::OUString & _sURL, const uno::Reference<uno::XInterface>& pContext, bool bNothrow ) throw (backend::InsufficientAccessRightsException, backend::BackendAccessException) { using namespace osl; if (_sURL.getLength() == 0) return false; DirectoryItem aDirItem; DirectoryItem::RC rc = DirectoryItem::get(_sURL, aDirItem); if (rc == DirectoryItem::E_None) rc = implNormalizeURL(_sURL,aDirItem); switch (rc) { case DirectoryItem::E_None: return true; case DirectoryItem::E_NOENT: return true; case DirectoryItem::E_ACCES: if (!bNothrow) { rtl::OUStringBuffer msg; msg.appendAscii("LocalBackend: Cannot normalize URL \"" ); msg.append(_sURL); msg.appendAscii("\" - InsufficientAccess"); throw backend::InsufficientAccessRightsException(msg.makeStringAndClear(),pContext,uno::Any()); } return false; default: if (!bNothrow) { rtl::OUStringBuffer msg; msg.appendAscii("LocalBackend: Cannot normalize URL \"" ); msg.append(_sURL); msg.appendAscii("\" - ").append(FileHelper::createOSLErrorString(rc)); throw backend::BackendAccessException(msg.makeStringAndClear(),pContext,uno::Any()); } return false; } } // --------------------------------------------------------------------------------------- static const sal_Unicode kComponentSeparator = '.' ; static const sal_Unicode kPathSeparator = '/' ; rtl::OUString componentToPath(const rtl::OUString& aComponent) { rtl::OUStringBuffer retCode ; retCode.append(kPathSeparator) ; retCode.append(aComponent.replace(kComponentSeparator, kPathSeparator)) ; return retCode.makeStringAndClear() ; } //------------------------------------------------------------------------------ rtl::OUString layeridToPath(const rtl::OUString& aLayerId) { sal_Int32 const nSplit = aLayerId.indexOf(k_cLayerIdSeparator); if (nSplit < 0) return componentToPath(aLayerId); rtl::OUString const aComponent= aLayerId.copy(0,nSplit); rtl::OUString const aSubid = aLayerId.copy(nSplit+1); rtl::OUStringBuffer retCode ; retCode.append(kPathSeparator) ; retCode.append(aComponent.replace(kComponentSeparator, kPathSeparator)) ; retCode.append(kPathSeparator) ; retCode.append(aSubid) ; return retCode.makeStringAndClear() ; } //------------------------------------------------------------------------------ bool checkOptionalArg(rtl::OUString& aArg) { if (aArg.getLength() && aArg[0] == sal_Unicode('?')) { aArg = aArg.copy(1); return true; } else { return false; } } //------------------------------------------------------------------------------ void fillFromBlankSeparated(const rtl::OUString& aList, uno::Sequence<rtl::OUString>& aTarget) { std::vector<rtl::OUString> tokens ; sal_Int32 nextToken = 0 ; do { tokens.push_back(aList.getToken(0, ' ', nextToken)) ; } while (nextToken >= 0) ; if (tokens.size() > 0) { aTarget.realloc(tokens.size()) ; std::vector<rtl::OUString>::const_iterator token ; sal_Int32 i = 0 ; for (token = tokens.begin() ; token != tokens.end() ; ++ token) { aTarget [i ++] = *token ; } } } //------------------------------------------------------------------------------ } } // namespace configmgr <commit_msg>INTEGRATION: CWS changefileheader (1.4.72); FILE MERGED 2008/04/01 15:06:46 thb 1.4.72.3: #i85898# Stripping all external header guards 2008/04/01 12:27:27 thb 1.4.72.2: #i85898# Stripping all external header guards 2008/03/31 12:22:48 rt 1.4.72.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: localfilehelper.cxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_configmgr.hxx" #include "localfilehelper.hxx" #include "filehelper.hxx" #include <rtl/ustrbuf.hxx> #include <osl/process.h> #include <vector> namespace configmgr { namespace localbe { //------------------------------------------------------------------------------ bool isValidFileURL (rtl::OUString const& _sFileURL) { using osl::File; rtl::OUString sSystemPath; return _sFileURL.getLength() && (File::E_None == File::getSystemPathFromFileURL(_sFileURL, sSystemPath)); } //------------------------------------------------------------------------------ void validateFileURL(const rtl::OUString& _sFileURL, const uno::Reference<uno::XInterface>& pContext) throw(css::configuration::InvalidBootstrapFileException) { if (!isValidFileURL( _sFileURL)) { rtl::OUStringBuffer sMsg; sMsg.appendAscii(" Not a Valid File URL: \""); sMsg.append(_sFileURL); sMsg.appendAscii("\""); throw com::sun::star::configuration::InvalidBootstrapFileException( sMsg.makeStringAndClear(),pContext, rtl::OUString() ) ; } } //------------------------------------------------------------------------------ void checkFileExists(const rtl::OUString& _sFileURL,const uno::Reference<uno::XInterface>& pContext) throw (backend::CannotConnectException) { if (!FileHelper::fileExists(_sFileURL)) { rtl::OUStringBuffer sMsg; sMsg.appendAscii(" No Such File or Directory: \""); sMsg.append(_sFileURL); sMsg.appendAscii("\""); throw backend::CannotConnectException(sMsg.makeStringAndClear(), pContext, uno::Any()) ; } } //------------------------------------------------------------------------------ void checkIfDirectory(const rtl::OUString& _sFileURL, const uno::Reference<uno::XInterface>& pContext) throw (backend::BackendSetupException) { if (!FileHelper::dirExists(_sFileURL)) { rtl::OUStringBuffer sMsg; sMsg.appendAscii(" File:\""); sMsg.append(_sFileURL); sMsg.appendAscii("\" Must be a Directory\""); throw backend::BackendSetupException(sMsg.makeStringAndClear(),pContext, uno::Any()) ; } } // --------------------------------------------------------------------------------------- bool implEnsureAbsoluteURL(rtl::OUString & _rsURL) // also strips embedded dots etc. { using osl::File; rtl::OUString sBasePath = _rsURL; OSL_VERIFY(osl_Process_E_None == osl_getProcessWorkingDir(&sBasePath.pData)); rtl::OUString sAbsolute; if ( File::E_None == File::getAbsoluteFileURL(sBasePath, _rsURL, sAbsolute)) { _rsURL = sAbsolute; return true; } else { OSL_ENSURE(false, "Could not get absolute file URL for valid URL"); return false; } } // --------------------------------------------------------------------------------------- osl::DirectoryItem::RC implNormalizeURL(rtl::OUString & _sURL, osl::DirectoryItem& aDirItem) { using namespace osl; OSL_PRECOND(aDirItem.is(), "Opened DirItem required"); static const sal_uInt32 cFileStatusMask = FileStatusMask_FileURL; FileStatus aFileStatus(cFileStatusMask); DirectoryItem::RC rc = aDirItem.getFileStatus(aFileStatus); if (rc == DirectoryItem::E_None) { rtl::OUString aNormalizedURL = aFileStatus.getFileURL(); if (aNormalizedURL.getLength() != 0) _sURL = aNormalizedURL; else rc = DirectoryItem::E_INVAL; } return rc; } // --------------------------------------------------------------------------------------- bool normalizeURL(rtl::OUString & _sURL, const uno::Reference<uno::XInterface>& pContext, bool bNothrow ) throw (backend::InsufficientAccessRightsException, backend::BackendAccessException) { using namespace osl; if (_sURL.getLength() == 0) return false; DirectoryItem aDirItem; DirectoryItem::RC rc = DirectoryItem::get(_sURL, aDirItem); if (rc == DirectoryItem::E_None) rc = implNormalizeURL(_sURL,aDirItem); switch (rc) { case DirectoryItem::E_None: return true; case DirectoryItem::E_NOENT: return true; case DirectoryItem::E_ACCES: if (!bNothrow) { rtl::OUStringBuffer msg; msg.appendAscii("LocalBackend: Cannot normalize URL \"" ); msg.append(_sURL); msg.appendAscii("\" - InsufficientAccess"); throw backend::InsufficientAccessRightsException(msg.makeStringAndClear(),pContext,uno::Any()); } return false; default: if (!bNothrow) { rtl::OUStringBuffer msg; msg.appendAscii("LocalBackend: Cannot normalize URL \"" ); msg.append(_sURL); msg.appendAscii("\" - ").append(FileHelper::createOSLErrorString(rc)); throw backend::BackendAccessException(msg.makeStringAndClear(),pContext,uno::Any()); } return false; } } // --------------------------------------------------------------------------------------- static const sal_Unicode kComponentSeparator = '.' ; static const sal_Unicode kPathSeparator = '/' ; rtl::OUString componentToPath(const rtl::OUString& aComponent) { rtl::OUStringBuffer retCode ; retCode.append(kPathSeparator) ; retCode.append(aComponent.replace(kComponentSeparator, kPathSeparator)) ; return retCode.makeStringAndClear() ; } //------------------------------------------------------------------------------ rtl::OUString layeridToPath(const rtl::OUString& aLayerId) { sal_Int32 const nSplit = aLayerId.indexOf(k_cLayerIdSeparator); if (nSplit < 0) return componentToPath(aLayerId); rtl::OUString const aComponent= aLayerId.copy(0,nSplit); rtl::OUString const aSubid = aLayerId.copy(nSplit+1); rtl::OUStringBuffer retCode ; retCode.append(kPathSeparator) ; retCode.append(aComponent.replace(kComponentSeparator, kPathSeparator)) ; retCode.append(kPathSeparator) ; retCode.append(aSubid) ; return retCode.makeStringAndClear() ; } //------------------------------------------------------------------------------ bool checkOptionalArg(rtl::OUString& aArg) { if (aArg.getLength() && aArg[0] == sal_Unicode('?')) { aArg = aArg.copy(1); return true; } else { return false; } } //------------------------------------------------------------------------------ void fillFromBlankSeparated(const rtl::OUString& aList, uno::Sequence<rtl::OUString>& aTarget) { std::vector<rtl::OUString> tokens ; sal_Int32 nextToken = 0 ; do { tokens.push_back(aList.getToken(0, ' ', nextToken)) ; } while (nextToken >= 0) ; if (tokens.size() > 0) { aTarget.realloc(tokens.size()) ; std::vector<rtl::OUString>::const_iterator token ; sal_Int32 i = 0 ; for (token = tokens.begin() ; token != tokens.end() ; ++ token) { aTarget [i ++] = *token ; } } } //------------------------------------------------------------------------------ } } // namespace configmgr <|endoftext|>
<commit_before>/******************************************************************************\ * File: shell.cpp * Purpose: Implementation of class wxExSTCShell * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/tokenzr.h> #include <wx/extension/shell.h> #include <wx/extension/app.h> #if wxUSE_GUI using namespace std; BEGIN_EVENT_TABLE(wxExSTCShell, wxExSTC) EVT_KEY_DOWN(wxExSTCShell::OnKey) EVT_MENU(wxID_PASTE, wxExSTCShell::OnCommand) END_EVENT_TABLE() wxExSTCShell::wxExSTCShell( wxWindow* parent, const wxString& prompt, const wxString& command_end, bool echo, int commands_save_in_config, long menu_flags) : wxExSTC(parent, menu_flags) , m_Command(wxEmptyString) , m_CommandEnd((command_end == wxEmptyString ? GetEOL(): command_end)) , m_CommandStartPosition(0) , m_Echo(echo) // take a char that is not likely to appear inside commands , m_CommandsInConfigDelimiter(wxChar(0x03)) , m_CommandsSaveInConfig(commands_save_in_config) , m_Prompt(prompt) { // Override defaults from config. SetEdgeMode(wxSTC_EDGE_NONE); ResetMargins(false); // do not reset divider margin // Start with a prompt. Prompt(); if (m_CommandsSaveInConfig > 0) { // Get all previous commands. wxStringTokenizer tkz(wxExApp::GetConfig("Shell"), m_CommandsInConfigDelimiter); while (tkz.HasMoreTokens()) { const wxString val = tkz.GetNextToken(); m_Commands.push_front(val); } } // Take care that m_CommandsIterator is valid. m_CommandsIterator = m_Commands.end(); } wxExSTCShell::~wxExSTCShell() { if (m_CommandsSaveInConfig > 0) { wxString values; int items = 0; for ( list < wxString >::reverse_iterator it = m_Commands.rbegin(); it != m_Commands.rend() && items < m_CommandsSaveInConfig; it++) { values += *it + m_CommandsInConfigDelimiter; items++; } wxExApp::SetConfig("Shell", values); } } const wxString wxExSTCShell::GetHistory() const { wxString commands; for ( list < wxString >::const_iterator it = m_Commands.begin(); it != m_Commands.end(); it++) { commands += *it + "\n"; } return commands; } void wxExSTCShell::KeepCommand() { m_Commands.remove(m_Command); m_Commands.push_back(m_Command); } void wxExSTCShell::OnCommand(wxCommandEvent& command) { switch (command.GetId()) { case wxID_PASTE: // Take care that we cannot paste somewhere inside. if (GetCurrentPos() < m_CommandStartPosition) { DocumentEnd(); } Paste(); break; default: command.Skip(); break; } } void wxExSTCShell::OnKey(wxKeyEvent& event) { const int key = event.GetKeyCode(); // Enter key pressed, we might have entered a command. if (key == WXK_RETURN) { // First get the command. SetTargetStart(GetTextLength()); SetTargetEnd(0); SetSearchFlags(wxSTC_FIND_REGEXP); if (SearchInTarget("^" + m_Prompt + ".*") != -1) { m_Command = GetText().substr( GetTargetStart() + m_Prompt.length(), GetTextLength() - 1); m_Command.Trim(); } if (m_Command.empty()) { Prompt(); } else if ( m_CommandEnd == GetEOL() || m_Command.EndsWith(m_CommandEnd)) { // We have a command. EmptyUndoBuffer(); // History command. if (m_Command == wxString("history") + (m_CommandEnd == GetEOL() ? wxString(wxEmptyString): m_CommandEnd)) { KeepCommand(); ShowHistory(); Prompt(); } // !.. command, get it from history. else if (m_Command.StartsWith("!")) { if (SetCommandFromHistory(m_Command.substr(1))) { AppendText(GetEOL() + m_Command); // We don't keep the command, so commands are not rearranged and // repeatingly calling !5 always gives the same command, just as bash does. wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(GetParent(), event); } else { Prompt(GetEOL() + m_Command + ": " + _("event not found")); } } // Other command, send to parent. else { KeepCommand(); wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(GetParent(), event); } m_Command.clear(); } else { if (m_Echo) event.Skip(); } m_CommandsIterator = m_Commands.end(); } // Up or down key pressed, and at the end of document. else if ((key == WXK_UP || key == WXK_DOWN) && GetCurrentPos() == GetTextLength()) { ShowCommand(key); } // Home key pressed. else if (key == WXK_HOME) { Home(); const wxString line = GetLine(GetCurrentLine()); if (line.StartsWith(m_Prompt)) { GotoPos(GetCurrentPos() + m_Prompt.length()); } } // Ctrl-Q pressed, used to stop processing. else if (event.GetModifiers() == wxMOD_CONTROL && key == 'Q') { wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND_STOP); wxPostEvent(GetParent(), event); } // Ctrl-V pressed, used for pasting as well. else if (event.GetModifiers() == wxMOD_CONTROL && key == 'V') { if (GetCurrentPos() < m_CommandStartPosition) DocumentEnd(); if (m_Echo) event.Skip(); } // Backspace or delete key pressed. else if (key == WXK_BACK || key == WXK_DELETE) { if (GetCurrentPos() <= m_CommandStartPosition) { // Ignore, so do nothing. } else { // Allow. if (m_Echo) event.Skip(); } } // The rest. else { // If we enter regular text and not already building a command, first goto end. if (event.GetModifiers() == wxMOD_NONE && key < WXK_START && GetCurrentPos() < m_CommandStartPosition) { DocumentEnd(); } m_CommandsIterator = m_Commands.end(); if (m_Echo) event.Skip(); } } void wxExSTCShell::Prompt(const wxString& text, bool add_eol) { if (!text.empty()) { AppendText(text); } if (GetTextLength() > 0 && add_eol) { AppendText(GetEOL()); } AppendText(m_Prompt); DocumentEnd(); m_CommandStartPosition = GetCurrentPos(); EmptyUndoBuffer(); } bool wxExSTCShell::SetCommandFromHistory(const wxString& short_command) { const int no_asked_for = atoi(short_command.c_str()); if (no_asked_for > 0) { int no = 1; for ( list < wxString >::const_iterator it = m_Commands.begin(); it != m_Commands.end(); it++) { if (no == no_asked_for) { m_Command = *it; return true; } no++; } } else { wxString short_command_check; if (m_CommandEnd == GetEOL()) { short_command_check = short_command; } else { short_command_check = short_command.substr( 0, short_command.length() - m_CommandEnd.length()); } // using a const_reverse_iterator here does not compile under MSW for ( list < wxString >::reverse_iterator it = m_Commands.rbegin(); it != m_Commands.rend(); it++) { const wxString command = *it; if (command.StartsWith(short_command_check)) { m_Command = command; return true; } } } return false; } void wxExSTCShell::ShowCommand(int key) { SetTargetStart(GetTextLength()); SetTargetEnd(0); SetSearchFlags(wxSTC_FIND_REGEXP); if (SearchInTarget("^" + m_Prompt + ".*") != -1) { SetTargetEnd(GetTextLength()); if (key == WXK_UP) { if (m_CommandsIterator != m_Commands.begin()) { m_CommandsIterator--; } } else { if (m_CommandsIterator != m_Commands.end()) { m_CommandsIterator++; } } if (m_CommandsIterator != m_Commands.end()) { ReplaceTarget(m_Prompt + *m_CommandsIterator); } else { ReplaceTarget(m_Prompt); } DocumentEnd(); } } void wxExSTCShell::ShowHistory() { int command_no = 1; for ( list < wxString >::iterator it = m_Commands.begin(); it != m_Commands.end(); it++) { const wxString command = *it; AppendText(wxString::Format("\n%d %s", command_no++, command.c_str())); } } #endif // wxUSE_GUI <commit_msg>added wxFAIL<commit_after>/******************************************************************************\ * File: shell.cpp * Purpose: Implementation of class wxExSTCShell * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/tokenzr.h> #include <wx/extension/shell.h> #include <wx/extension/app.h> #if wxUSE_GUI using namespace std; BEGIN_EVENT_TABLE(wxExSTCShell, wxExSTC) EVT_KEY_DOWN(wxExSTCShell::OnKey) EVT_MENU(wxID_PASTE, wxExSTCShell::OnCommand) END_EVENT_TABLE() wxExSTCShell::wxExSTCShell( wxWindow* parent, const wxString& prompt, const wxString& command_end, bool echo, int commands_save_in_config, long menu_flags) : wxExSTC(parent, menu_flags) , m_Command(wxEmptyString) , m_CommandEnd((command_end == wxEmptyString ? GetEOL(): command_end)) , m_CommandStartPosition(0) , m_Echo(echo) // take a char that is not likely to appear inside commands , m_CommandsInConfigDelimiter(wxChar(0x03)) , m_CommandsSaveInConfig(commands_save_in_config) , m_Prompt(prompt) { // Override defaults from config. SetEdgeMode(wxSTC_EDGE_NONE); ResetMargins(false); // do not reset divider margin // Start with a prompt. Prompt(); if (m_CommandsSaveInConfig > 0) { // Get all previous commands. wxStringTokenizer tkz(wxExApp::GetConfig("Shell"), m_CommandsInConfigDelimiter); while (tkz.HasMoreTokens()) { const wxString val = tkz.GetNextToken(); m_Commands.push_front(val); } } // Take care that m_CommandsIterator is valid. m_CommandsIterator = m_Commands.end(); } wxExSTCShell::~wxExSTCShell() { if (m_CommandsSaveInConfig > 0) { wxString values; int items = 0; for ( list < wxString >::reverse_iterator it = m_Commands.rbegin(); it != m_Commands.rend() && items < m_CommandsSaveInConfig; it++) { values += *it + m_CommandsInConfigDelimiter; items++; } wxExApp::SetConfig("Shell", values); } } const wxString wxExSTCShell::GetHistory() const { wxString commands; for ( list < wxString >::const_iterator it = m_Commands.begin(); it != m_Commands.end(); it++) { commands += *it + "\n"; } return commands; } void wxExSTCShell::KeepCommand() { m_Commands.remove(m_Command); m_Commands.push_back(m_Command); } void wxExSTCShell::OnCommand(wxCommandEvent& command) { switch (command.GetId()) { case wxID_PASTE: // Take care that we cannot paste somewhere inside. if (GetCurrentPos() < m_CommandStartPosition) { DocumentEnd(); } Paste(); break; default: wxFAIL; break; } } void wxExSTCShell::OnKey(wxKeyEvent& event) { const int key = event.GetKeyCode(); // Enter key pressed, we might have entered a command. if (key == WXK_RETURN) { // First get the command. SetTargetStart(GetTextLength()); SetTargetEnd(0); SetSearchFlags(wxSTC_FIND_REGEXP); if (SearchInTarget("^" + m_Prompt + ".*") != -1) { m_Command = GetText().substr( GetTargetStart() + m_Prompt.length(), GetTextLength() - 1); m_Command.Trim(); } if (m_Command.empty()) { Prompt(); } else if ( m_CommandEnd == GetEOL() || m_Command.EndsWith(m_CommandEnd)) { // We have a command. EmptyUndoBuffer(); // History command. if (m_Command == wxString("history") + (m_CommandEnd == GetEOL() ? wxString(wxEmptyString): m_CommandEnd)) { KeepCommand(); ShowHistory(); Prompt(); } // !.. command, get it from history. else if (m_Command.StartsWith("!")) { if (SetCommandFromHistory(m_Command.substr(1))) { AppendText(GetEOL() + m_Command); // We don't keep the command, so commands are not rearranged and // repeatingly calling !5 always gives the same command, just as bash does. wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(GetParent(), event); } else { Prompt(GetEOL() + m_Command + ": " + _("event not found")); } } // Other command, send to parent. else { KeepCommand(); wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(GetParent(), event); } m_Command.clear(); } else { if (m_Echo) event.Skip(); } m_CommandsIterator = m_Commands.end(); } // Up or down key pressed, and at the end of document. else if ((key == WXK_UP || key == WXK_DOWN) && GetCurrentPos() == GetTextLength()) { ShowCommand(key); } // Home key pressed. else if (key == WXK_HOME) { Home(); const wxString line = GetLine(GetCurrentLine()); if (line.StartsWith(m_Prompt)) { GotoPos(GetCurrentPos() + m_Prompt.length()); } } // Ctrl-Q pressed, used to stop processing. else if (event.GetModifiers() == wxMOD_CONTROL && key == 'Q') { wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND_STOP); wxPostEvent(GetParent(), event); } // Ctrl-V pressed, used for pasting as well. else if (event.GetModifiers() == wxMOD_CONTROL && key == 'V') { if (GetCurrentPos() < m_CommandStartPosition) DocumentEnd(); if (m_Echo) event.Skip(); } // Backspace or delete key pressed. else if (key == WXK_BACK || key == WXK_DELETE) { if (GetCurrentPos() <= m_CommandStartPosition) { // Ignore, so do nothing. } else { // Allow. if (m_Echo) event.Skip(); } } // The rest. else { // If we enter regular text and not already building a command, first goto end. if (event.GetModifiers() == wxMOD_NONE && key < WXK_START && GetCurrentPos() < m_CommandStartPosition) { DocumentEnd(); } m_CommandsIterator = m_Commands.end(); if (m_Echo) event.Skip(); } } void wxExSTCShell::Prompt(const wxString& text, bool add_eol) { if (!text.empty()) { AppendText(text); } if (GetTextLength() > 0 && add_eol) { AppendText(GetEOL()); } AppendText(m_Prompt); DocumentEnd(); m_CommandStartPosition = GetCurrentPos(); EmptyUndoBuffer(); } bool wxExSTCShell::SetCommandFromHistory(const wxString& short_command) { const int no_asked_for = atoi(short_command.c_str()); if (no_asked_for > 0) { int no = 1; for ( list < wxString >::const_iterator it = m_Commands.begin(); it != m_Commands.end(); it++) { if (no == no_asked_for) { m_Command = *it; return true; } no++; } } else { wxString short_command_check; if (m_CommandEnd == GetEOL()) { short_command_check = short_command; } else { short_command_check = short_command.substr( 0, short_command.length() - m_CommandEnd.length()); } // using a const_reverse_iterator here does not compile under MSW for ( list < wxString >::reverse_iterator it = m_Commands.rbegin(); it != m_Commands.rend(); it++) { const wxString command = *it; if (command.StartsWith(short_command_check)) { m_Command = command; return true; } } } return false; } void wxExSTCShell::ShowCommand(int key) { SetTargetStart(GetTextLength()); SetTargetEnd(0); SetSearchFlags(wxSTC_FIND_REGEXP); if (SearchInTarget("^" + m_Prompt + ".*") != -1) { SetTargetEnd(GetTextLength()); if (key == WXK_UP) { if (m_CommandsIterator != m_Commands.begin()) { m_CommandsIterator--; } } else { if (m_CommandsIterator != m_Commands.end()) { m_CommandsIterator++; } } if (m_CommandsIterator != m_Commands.end()) { ReplaceTarget(m_Prompt + *m_CommandsIterator); } else { ReplaceTarget(m_Prompt); } DocumentEnd(); } } void wxExSTCShell::ShowHistory() { int command_no = 1; for ( list < wxString >::iterator it = m_Commands.begin(); it != m_Commands.end(); it++) { const wxString command = *it; AppendText(wxString::Format("\n%d %s", command_no++, command.c_str())); } } #endif // wxUSE_GUI <|endoftext|>
<commit_before>#include <nan.h> #include "oc-dev-addr.h" #include "../common.h" using namespace v8; Local<Object> js_OCDevAddr(OCDevAddr *address) { uint32_t addressIndex; Local<Object> returnValue = NanNew<Object>(); // addr.addr Local<Array> addrAddr = NanNew<Array>(DEV_ADDR_SIZE_MAX); for (addressIndex = 0; addressIndex < DEV_ADDR_SIZE_MAX; addressIndex++) { addrAddr->Set(addressIndex, NanNew<Number>(address->addr[addressIndex])); } returnValue->Set(NanNew<String>("addr"), addrAddr); return returnValue; } bool c_OCDevAddr(Local<Object> jsDevAddr, OCDevAddr *address) { uint32_t addressIndex; uint8_t addr[DEV_ADDR_SIZE_MAX] = {0}; Local<Value> size = jsDevAddr->Get(NanNew<String>("size")); VALIDATE_VALUE_TYPE(size, IsNumber, "addr.size", false); Local<Value> addrValue = jsDevAddr->Get(NanNew<String>("addr")); VALIDATE_VALUE_TYPE(addrValue, IsArray, "addr.addr", false); Local<Array> addrArray = Local<Array>::Cast(addrValue); uint32_t addrLength = addrArray->Length(); if (addrLength > DEV_ADDR_SIZE_MAX) { NanThrowRangeError( "OCDevAddr: Number of JS structure address bytes exceeds " "DEV_ADDR_SIZE_MAX"); return false; } // Grab each address byte, making sure it's a number for (addressIndex = 0; addressIndex < DEV_ADDR_SIZE_MAX; addressIndex++) { Local<Value> addressItem = addrArray->Get(addressIndex); VALIDATE_VALUE_TYPE(addressItem, IsNumber, "addr.addr item", false); addr[addressIndex] = addressItem->Uint32Value(); } return true; } <commit_msg>OCDevAddr: Update to reflect new structure<commit_after>#include <nan.h> #include "oc-dev-addr.h" #include "../common.h" extern "C" { #include <string.h> } using namespace v8; Local<Object> js_OCDevAddr(OCDevAddr *address) { uint32_t index; Local<Object> returnValue = NanNew<Object>(); // addr.adapter returnValue->Set(NanNew<String>("adapter"), NanNew<Number>(address->adapter)); // addr.flags returnValue->Set(NanNew<String>("flags"), NanNew<Number>(address->flags)); // addr.addr Local<Array> addr = NanNew<Array>(MAX_ADDR_STR_SIZE); for (index = 0; index < MAX_ADDR_STR_SIZE; index++) { addr->Set(index, NanNew<Number>(address->addr[index])); } returnValue->Set(NanNew<String>("addr"), addr); // addr.interface returnValue->Set(NanNew<String>("interface"), NanNew<Number>(address->interface)); // addr.port returnValue->Set(NanNew<String>("port"), NanNew<Number>(address->port)); // addr.identity Local<Array> identity = NanNew<Array>(address->identity.id_length); for (index = 0; index < address->identity.id_length; index++) { identity->Set(index, NanNew<Number>(address->identity.id[index])); } returnValue->Set(NanNew<String>("identity"), identity); return returnValue; } bool c_OCDevAddr(Local<Object> jsDevAddr, OCDevAddr *address) { uint32_t index, length; OCDevAddr local; // addr.adapter Local<Value> adapter = jsDevAddr->Get(NanNew<String>("adapter")); VALIDATE_VALUE_TYPE(adapter, IsNumber, "addr.adapter", false); local.adapter = (OCTransportAdapter)adapter->Uint32Value(); // addr.flags Local<Value> flags = jsDevAddr->Get(NanNew<String>("flags")); VALIDATE_VALUE_TYPE(flags, IsNumber, "addr.flags", false); local.flags = (OCTransportFlags)flags->Uint32Value(); // addr.addr Local<Value> addr = jsDevAddr->Get(NanNew<String>("addr")); VALIDATE_VALUE_TYPE(addr, IsArray, "addr.addr", false); Local<Array> addrArray = Local<Array>::Cast(addr); length = addrArray->Length(); if (length > MAX_ADDR_STR_SIZE) { NanThrowRangeError( "OCDevAddr: Number of JS structure address bytes exceeds " "MAX_ADDR_STR_SIZE"); return false; } for (index = 0; index < MAX_ADDR_STR_SIZE; index++) { if (index < length) { Local<Value> addressItem = addrArray->Get(index); VALIDATE_VALUE_TYPE(addressItem, IsNumber, "addr.addr item", false); local.addr[index] = (char)addressItem->Uint32Value(); } else { local.addr[index] = 0; } } // addr.interface Local<Value> interface = jsDevAddr->Get(NanNew<String>("interface")); VALIDATE_VALUE_TYPE(interface, IsNumber, "addr.interface", false); local.interface = interface->Uint32Value(); // addr.port Local<Value> port = jsDevAddr->Get(NanNew<String>("port")); VALIDATE_VALUE_TYPE(port, IsNumber, "addr.port", false); local.port = port->Uint32Value(); // addr.identity Local<Value> identity = jsDevAddr->Get(NanNew<String>("identity")); VALIDATE_VALUE_TYPE(identity, IsArray, "addr.identity", false); Local<Array> identityArray = Local<Array>::Cast(identity); length = identityArray->Length(); if (length > MAX_IDENTITY_SIZE) { NanThrowRangeError( "OCDevAddr: Number of JS structure identity bytes exceeds " "MAX_IDENTITY_SIZE"); return false; } for (index = 0; index < MAX_IDENTITY_SIZE; index++) { if (index < length) { Local<Value> identityItem = identityArray->Get(index); VALIDATE_VALUE_TYPE(identityItem, IsNumber, "addr.identity.id item", false); local.identity.id[index] = (unsigned char)identityItem->Uint32Value(); } else { local.identity.id[index] = 0; } } local.identity.id_length = length; // We only touch the structure we're supposed to fill in if all retrieval from // JS has gone well memcpy(address, &local, sizeof(OCDevAddr)); return true; } <|endoftext|>
<commit_before>/* * Copyright (C) 2009, 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #ifndef URBI_EXPORT_HH # define URBI_SDK_EXPORT_HH # include <libport/compiler.hh> # ifdef BUILDING_URBI_SDK # define URBI_SDK_API ATTRIBUTE_DLLEXPORT # else # define URBI_SDK_API ATTRIBUTE_DLLIMPORT # endif #endif // URBI_EXPORT_HH <commit_msg>urbi: fix cpp guard.<commit_after>/* * Copyright (C) 2009, 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #ifndef URBI_EXPORT_HH # define URBI_EXPORT_HH # include <libport/compiler.hh> # ifdef BUILDING_URBI_SDK # define URBI_SDK_API ATTRIBUTE_DLLEXPORT # else # define URBI_SDK_API ATTRIBUTE_DLLIMPORT # endif #endif // URBI_EXPORT_HH <|endoftext|>
<commit_before>/* Copyright 2017-2018 CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "skittleItem.h" #include <QtGui/QIcon> #include <QtWidgets/QAction> #include <QtSvg/QSvgRenderer> #include <twoDModel/engine/model/constants.h> using namespace twoDModel::items; SkittleItem::SkittleItem(const QPointF &position) : SolidItem() , mStartPosition(QPointF()) , mStartRotation(0.0f) , mSvgRenderer(new QSvgRenderer) { mSvgRenderer->load(QString(":/icons/2d_can.svg")); setPos(position); setZValue(1); setTransformOriginPoint(boundingRect().center()); } SkittleItem::~SkittleItem() { delete mSvgRenderer; } QAction *SkittleItem::skittleTool() { QAction * const result = new QAction(QIcon(":/icons/2d_can.svg"), tr("Can (C)"), nullptr); result->setShortcut(QKeySequence(Qt::Key_C)); result->setCheckable(true); return result; } QRectF SkittleItem::boundingRect() const { return QRectF({0, 0}, skittleSize); } void SkittleItem::drawItem(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option) Q_UNUSED(widget) mSvgRenderer->render(painter, boundingRect()); } QDomElement SkittleItem::serialize(QDomElement &element) const { QDomElement skittleNode = AbstractItem::serialize(element); skittleNode.setTagName("skittle"); skittleNode.setAttribute("x", QString::number(x1() + scenePos().x())); skittleNode.setAttribute("y", QString::number(y1() + scenePos().y())); skittleNode.setAttribute("markerX", QString::number(x1() + mStartPosition.x())); skittleNode.setAttribute("markerY", QString::number(y1() + mStartPosition.y())); skittleNode.setAttribute("rotation", QString::number(rotation())); skittleNode.setAttribute("startRotation", QString::number(mStartRotation)); return skittleNode; } void SkittleItem::deserialize(const QDomElement &element) { AbstractItem::deserialize(element); qreal x = element.attribute("x", "0").toDouble(); qreal y = element.attribute("y", "0").toDouble(); qreal markerX = element.attribute("markerX", "0").toDouble(); qreal markerY = element.attribute("markerY", "0").toDouble(); qreal rotation = element.attribute("rotation", "0").toDouble(); mStartRotation = element.attribute("startRotation", "0").toDouble(); setPos(QPointF(x, y) + boundingRect().center()); setTransformOriginPoint(boundingRect().center()); mStartPosition = {markerX, markerY}; setRotation(rotation); emit x1Changed(x1()); } void SkittleItem::saveStartPosition() { mStartPosition = pos(); mStartRotation = rotation(); emit x1Changed(x1()); } void SkittleItem::returnToStartPosition() { setPos(mStartPosition); setRotation(mStartRotation); emit x1Changed(x1()); } QPolygonF SkittleItem::collidingPolygon() const { return QPolygonF(QRectF(scenePos(), skittleSize - QSize(1, 1))); } qreal SkittleItem::angularDamping() const { return 6.0f; } qreal SkittleItem::linearDamping() const { return 6.0f; } QPainterPath SkittleItem::path() const { QPainterPath path; QPolygonF collidingPlgn = collidingPolygon(); QMatrix m; m.rotate(rotation()); const QPointF firstP = collidingPlgn.at(0); collidingPlgn.translate(-firstP.x(), -firstP.y()); path.addEllipse(collidingPlgn.boundingRect()); path = m.map(path); path.translate(firstP.x(), firstP.y()); return path; } bool SkittleItem::isCircle() const { return true; } qreal SkittleItem::mass() const { return 0.05; } qreal SkittleItem::friction() const { return 0.2; } SolidItem::BodyType SkittleItem::bodyType() const { return SolidItem::DYNAMIC; } <commit_msg>fix deserialization process for skittle<commit_after>/* Copyright 2017-2018 CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "skittleItem.h" #include <QtGui/QIcon> #include <QtWidgets/QAction> #include <QtSvg/QSvgRenderer> #include <twoDModel/engine/model/constants.h> using namespace twoDModel::items; SkittleItem::SkittleItem(const QPointF &position) : SolidItem() , mStartPosition(QPointF()) , mStartRotation(0.0f) , mSvgRenderer(new QSvgRenderer) { mSvgRenderer->load(QString(":/icons/2d_can.svg")); setPos(position); setZValue(1); setTransformOriginPoint(boundingRect().center()); } SkittleItem::~SkittleItem() { delete mSvgRenderer; } QAction *SkittleItem::skittleTool() { QAction * const result = new QAction(QIcon(":/icons/2d_can.svg"), tr("Can (C)"), nullptr); result->setShortcut(QKeySequence(Qt::Key_C)); result->setCheckable(true); return result; } QRectF SkittleItem::boundingRect() const { return QRectF({0, 0}, skittleSize); } void SkittleItem::drawItem(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option) Q_UNUSED(widget) mSvgRenderer->render(painter, boundingRect()); } QDomElement SkittleItem::serialize(QDomElement &element) const { QDomElement skittleNode = AbstractItem::serialize(element); skittleNode.setTagName("skittle"); skittleNode.setAttribute("x", QString::number(x1() + scenePos().x())); skittleNode.setAttribute("y", QString::number(y1() + scenePos().y())); skittleNode.setAttribute("markerX", QString::number(x1() + mStartPosition.x())); skittleNode.setAttribute("markerY", QString::number(y1() + mStartPosition.y())); skittleNode.setAttribute("rotation", QString::number(rotation())); skittleNode.setAttribute("startRotation", QString::number(mStartRotation)); return skittleNode; } void SkittleItem::deserialize(const QDomElement &element) { AbstractItem::deserialize(element); qreal x = element.attribute("x", "0").toDouble(); qreal y = element.attribute("y", "0").toDouble(); qreal markerX = element.attribute("markerX", "0").toDouble(); qreal markerY = element.attribute("markerY", "0").toDouble(); qreal rotation = element.attribute("rotation", "0").toDouble(); mStartRotation = element.attribute("startRotation", "0").toDouble(); setPos(QPointF(x, y)); setTransformOriginPoint(boundingRect().center()); mStartPosition = {markerX, markerY}; setRotation(rotation); emit x1Changed(x1()); } void SkittleItem::saveStartPosition() { mStartPosition = pos(); mStartRotation = rotation(); emit x1Changed(x1()); } void SkittleItem::returnToStartPosition() { setPos(mStartPosition); setRotation(mStartRotation); emit x1Changed(x1()); } QPolygonF SkittleItem::collidingPolygon() const { return QPolygonF(QRectF(scenePos(), skittleSize - QSize(1, 1))); } qreal SkittleItem::angularDamping() const { return 6.0f; } qreal SkittleItem::linearDamping() const { return 6.0f; } QPainterPath SkittleItem::path() const { QPainterPath path; QPolygonF collidingPlgn = collidingPolygon(); QMatrix m; m.rotate(rotation()); const QPointF firstP = collidingPlgn.at(0); collidingPlgn.translate(-firstP.x(), -firstP.y()); path.addEllipse(collidingPlgn.boundingRect()); path = m.map(path); path.translate(firstP.x(), firstP.y()); return path; } bool SkittleItem::isCircle() const { return true; } qreal SkittleItem::mass() const { return 0.05; } qreal SkittleItem::friction() const { return 0.2; } SolidItem::BodyType SkittleItem::bodyType() const { return SolidItem::DYNAMIC; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: TIndexes.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2005-03-23 09:40:18 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CONNECTIVITY_INDEXESHELPER_HXX #include "connectivity/TIndexes.hxx" #endif #ifndef CONNECTIVITY_INDEXHELPER_HXX_ #include "connectivity/TIndex.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_INDEXTYPE_HPP_ #include <com/sun/star/sdbc/IndexType.hpp> #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include <connectivity/dbtools.hxx> #endif #ifndef CONNECTIVITY_TABLEHELPER_HXX #include "connectivity/TTableHelper.hxx" #endif #ifndef CONNECTIVITY_CONNECTION_HXX #include "TConnection.hxx" #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif using namespace connectivity; using namespace connectivity::sdbcx; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace cppu; typedef connectivity::sdbcx::OCollection OCollection_TYPE; // ----------------------------------------------------------------------------- OIndexesHelper::OIndexesHelper(OTableHelper* _pTable, ::osl::Mutex& _rMutex, const ::std::vector< ::rtl::OUString> &_rVector ) : OCollection(*_pTable,sal_True,_rMutex,_rVector) ,m_pTable(_pTable) { } // ----------------------------------------------------------------------------- sdbcx::ObjectType OIndexesHelper::createObject(const ::rtl::OUString& _rName) { sdbcx::ObjectType xRet; ::rtl::OUString aName,aQualifier; sal_Int32 nLen = _rName.indexOf('.'); if ( nLen != -1 ) { aQualifier = _rName.copy(0,nLen); aName = _rName.copy(nLen+1); } else aName = _rName; ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap(); ::rtl::OUString aSchema,aTable; m_pTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_SCHEMANAME)) >>= aSchema; m_pTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME)) >>= aTable; Any aCatalog = m_pTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME)); Reference< XResultSet > xResult = m_pTable->getMetaData()->getIndexInfo(aCatalog,aSchema,aTable,sal_False,sal_False); if ( xResult.is() ) { Reference< XRow > xRow(xResult,UNO_QUERY); while( xResult->next() ) { sal_Bool bUnique = !xRow->getBoolean(4); if((!aQualifier.getLength() || xRow->getString(5) == aQualifier ) && xRow->getString(6) == aName) { sal_Int32 nClustered = xRow->getShort(7); sal_Bool bPrimarKeyIndex = sal_False; xRow = NULL; xResult = NULL; try { xResult = m_pTable->getMetaData()->getPrimaryKeys(aCatalog,aSchema,aTable); xRow.set(xResult,UNO_QUERY); if ( xRow.is() && xResult->next() ) // there can be only one primary key { bPrimarKeyIndex = xRow->getString(6) == aName; } } catch(Exception) { } OIndexHelper* pRet = new OIndexHelper(m_pTable,aName,aQualifier,bUnique, bPrimarKeyIndex, nClustered == IndexType::CLUSTERED); xRet = pRet; break; } } } return xRet; } // ------------------------------------------------------------------------- void OIndexesHelper::impl_refresh() throw(RuntimeException) { m_pTable->refreshIndexes(); } // ------------------------------------------------------------------------- Reference< XPropertySet > OIndexesHelper::createEmptyObject() { return new OIndexHelper(m_pTable); } // ------------------------------------------------------------------------- // XAppend void OIndexesHelper::appendObject( const Reference< XPropertySet >& descriptor ) { ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap(); ::rtl::OUString aName = comphelper::getString(descriptor->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME))); if ( m_pElements->exists(aName) ) throw ElementExistException(aName,static_cast<XTypeProvider*>(this)); if(!m_pTable->isNew()) { ::rtl::OUStringBuffer aSql( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("CREATE "))); ::rtl::OUString aQuote = m_pTable->getMetaData()->getIdentifierQuoteString( ); ::rtl::OUString aDot = ::rtl::OUString::createFromAscii("."); if(comphelper::getBOOL(descriptor->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_ISUNIQUE)))) aSql.appendAscii("UNIQUE "); aSql.appendAscii("INDEX "); ::rtl::OUString aCatalog,aSchema,aTable; dbtools::qualifiedNameComponents(m_pTable->getMetaData(),m_pTable->getName(),aCatalog,aSchema,aTable,::dbtools::eInDataManipulation); ::rtl::OUString aComposedName; dbtools::composeTableName(m_pTable->getMetaData(),aCatalog,aSchema,aTable,aComposedName,sal_True,::dbtools::eInIndexDefinitions); if ( aName.getLength() ) { aSql.append(::dbtools::quoteName( aQuote,aName )); aSql.appendAscii(" ON "); aSql.append(aComposedName); aSql.appendAscii(" ( "); Reference<XColumnsSupplier> xColumnSup(descriptor,UNO_QUERY); Reference<XIndexAccess> xColumns(xColumnSup->getColumns(),UNO_QUERY); Reference< XPropertySet > xColProp; sal_Bool bAddIndexAppendix = ::dbtools::isDataSourcePropertyEnabled(m_pTable->getConnection(),::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AddIndexAppendix")),sal_True); sal_Int32 nCount = xColumns->getCount(); for(sal_Int32 i = 0 ; i < nCount; ++i) { xColProp.set(xColumns->getByIndex(i),UNO_QUERY); aSql.append(::dbtools::quoteName( aQuote,comphelper::getString(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME))))); if ( bAddIndexAppendix ) { aSql.appendAscii(any2bool(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_ISASCENDING))) ? " ASC" : " DESC"); } aSql.appendAscii(","); } aSql.setCharAt(aSql.getLength()-1,')'); } else { aSql.append(aComposedName); Reference<XColumnsSupplier> xColumnSup(descriptor,UNO_QUERY); Reference<XIndexAccess> xColumns(xColumnSup->getColumns(),UNO_QUERY); Reference< XPropertySet > xColProp; if(xColumns->getCount() != 1) throw SQLException(); xColumns->getByIndex(0) >>= xColProp; aSql.append(aDot); aSql.append(::dbtools::quoteName( aQuote,comphelper::getString(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME))))); } Reference< XStatement > xStmt = m_pTable->getConnection()->createStatement( ); if ( xStmt.is() ) { ::rtl::OUString sSql = aSql.makeStringAndClear(); xStmt->execute(sSql); ::comphelper::disposeComponent(xStmt); } } } // ------------------------------------------------------------------------- // XDrop void OIndexesHelper::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName) { if(!m_pTable->isNew()) { ::rtl::OUString aName,aSchema; sal_Int32 nLen = _sElementName.indexOf('.'); if(nLen != -1) aSchema = _sElementName.copy(0,nLen); aName = _sElementName.copy(nLen+1); ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP INDEX "); ::rtl::OUString aComposedName = dbtools::composeTableName(m_pTable->getMetaData(),m_pTable,sal_True,::dbtools::eInIndexDefinitions); ::rtl::OUString sIndexName,sTemp; dbtools::composeTableName(m_pTable->getMetaData(),sTemp,aSchema,aName,sIndexName,sal_True,::dbtools::eInIndexDefinitions,sal_True,sal_True); aSql += sIndexName + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ON ")) + aComposedName; Reference< XStatement > xStmt = m_pTable->getConnection()->createStatement( ); if ( xStmt.is() ) { xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); } } } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS ooo19126 (1.6.62); FILE MERGED 2005/09/05 17:22:51 rt 1.6.62.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TIndexes.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-08 05:11:32 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONNECTIVITY_INDEXESHELPER_HXX #include "connectivity/TIndexes.hxx" #endif #ifndef CONNECTIVITY_INDEXHELPER_HXX_ #include "connectivity/TIndex.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_INDEXTYPE_HPP_ #include <com/sun/star/sdbc/IndexType.hpp> #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include <connectivity/dbtools.hxx> #endif #ifndef CONNECTIVITY_TABLEHELPER_HXX #include "connectivity/TTableHelper.hxx" #endif #ifndef CONNECTIVITY_CONNECTION_HXX #include "TConnection.hxx" #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif using namespace connectivity; using namespace connectivity::sdbcx; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace cppu; typedef connectivity::sdbcx::OCollection OCollection_TYPE; // ----------------------------------------------------------------------------- OIndexesHelper::OIndexesHelper(OTableHelper* _pTable, ::osl::Mutex& _rMutex, const ::std::vector< ::rtl::OUString> &_rVector ) : OCollection(*_pTable,sal_True,_rMutex,_rVector) ,m_pTable(_pTable) { } // ----------------------------------------------------------------------------- sdbcx::ObjectType OIndexesHelper::createObject(const ::rtl::OUString& _rName) { sdbcx::ObjectType xRet; ::rtl::OUString aName,aQualifier; sal_Int32 nLen = _rName.indexOf('.'); if ( nLen != -1 ) { aQualifier = _rName.copy(0,nLen); aName = _rName.copy(nLen+1); } else aName = _rName; ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap(); ::rtl::OUString aSchema,aTable; m_pTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_SCHEMANAME)) >>= aSchema; m_pTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME)) >>= aTable; Any aCatalog = m_pTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME)); Reference< XResultSet > xResult = m_pTable->getMetaData()->getIndexInfo(aCatalog,aSchema,aTable,sal_False,sal_False); if ( xResult.is() ) { Reference< XRow > xRow(xResult,UNO_QUERY); while( xResult->next() ) { sal_Bool bUnique = !xRow->getBoolean(4); if((!aQualifier.getLength() || xRow->getString(5) == aQualifier ) && xRow->getString(6) == aName) { sal_Int32 nClustered = xRow->getShort(7); sal_Bool bPrimarKeyIndex = sal_False; xRow = NULL; xResult = NULL; try { xResult = m_pTable->getMetaData()->getPrimaryKeys(aCatalog,aSchema,aTable); xRow.set(xResult,UNO_QUERY); if ( xRow.is() && xResult->next() ) // there can be only one primary key { bPrimarKeyIndex = xRow->getString(6) == aName; } } catch(Exception) { } OIndexHelper* pRet = new OIndexHelper(m_pTable,aName,aQualifier,bUnique, bPrimarKeyIndex, nClustered == IndexType::CLUSTERED); xRet = pRet; break; } } } return xRet; } // ------------------------------------------------------------------------- void OIndexesHelper::impl_refresh() throw(RuntimeException) { m_pTable->refreshIndexes(); } // ------------------------------------------------------------------------- Reference< XPropertySet > OIndexesHelper::createEmptyObject() { return new OIndexHelper(m_pTable); } // ------------------------------------------------------------------------- // XAppend void OIndexesHelper::appendObject( const Reference< XPropertySet >& descriptor ) { ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap(); ::rtl::OUString aName = comphelper::getString(descriptor->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME))); if ( m_pElements->exists(aName) ) throw ElementExistException(aName,static_cast<XTypeProvider*>(this)); if(!m_pTable->isNew()) { ::rtl::OUStringBuffer aSql( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("CREATE "))); ::rtl::OUString aQuote = m_pTable->getMetaData()->getIdentifierQuoteString( ); ::rtl::OUString aDot = ::rtl::OUString::createFromAscii("."); if(comphelper::getBOOL(descriptor->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_ISUNIQUE)))) aSql.appendAscii("UNIQUE "); aSql.appendAscii("INDEX "); ::rtl::OUString aCatalog,aSchema,aTable; dbtools::qualifiedNameComponents(m_pTable->getMetaData(),m_pTable->getName(),aCatalog,aSchema,aTable,::dbtools::eInDataManipulation); ::rtl::OUString aComposedName; dbtools::composeTableName(m_pTable->getMetaData(),aCatalog,aSchema,aTable,aComposedName,sal_True,::dbtools::eInIndexDefinitions); if ( aName.getLength() ) { aSql.append(::dbtools::quoteName( aQuote,aName )); aSql.appendAscii(" ON "); aSql.append(aComposedName); aSql.appendAscii(" ( "); Reference<XColumnsSupplier> xColumnSup(descriptor,UNO_QUERY); Reference<XIndexAccess> xColumns(xColumnSup->getColumns(),UNO_QUERY); Reference< XPropertySet > xColProp; sal_Bool bAddIndexAppendix = ::dbtools::isDataSourcePropertyEnabled(m_pTable->getConnection(),::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AddIndexAppendix")),sal_True); sal_Int32 nCount = xColumns->getCount(); for(sal_Int32 i = 0 ; i < nCount; ++i) { xColProp.set(xColumns->getByIndex(i),UNO_QUERY); aSql.append(::dbtools::quoteName( aQuote,comphelper::getString(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME))))); if ( bAddIndexAppendix ) { aSql.appendAscii(any2bool(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_ISASCENDING))) ? " ASC" : " DESC"); } aSql.appendAscii(","); } aSql.setCharAt(aSql.getLength()-1,')'); } else { aSql.append(aComposedName); Reference<XColumnsSupplier> xColumnSup(descriptor,UNO_QUERY); Reference<XIndexAccess> xColumns(xColumnSup->getColumns(),UNO_QUERY); Reference< XPropertySet > xColProp; if(xColumns->getCount() != 1) throw SQLException(); xColumns->getByIndex(0) >>= xColProp; aSql.append(aDot); aSql.append(::dbtools::quoteName( aQuote,comphelper::getString(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME))))); } Reference< XStatement > xStmt = m_pTable->getConnection()->createStatement( ); if ( xStmt.is() ) { ::rtl::OUString sSql = aSql.makeStringAndClear(); xStmt->execute(sSql); ::comphelper::disposeComponent(xStmt); } } } // ------------------------------------------------------------------------- // XDrop void OIndexesHelper::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName) { if(!m_pTable->isNew()) { ::rtl::OUString aName,aSchema; sal_Int32 nLen = _sElementName.indexOf('.'); if(nLen != -1) aSchema = _sElementName.copy(0,nLen); aName = _sElementName.copy(nLen+1); ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP INDEX "); ::rtl::OUString aComposedName = dbtools::composeTableName(m_pTable->getMetaData(),m_pTable,sal_True,::dbtools::eInIndexDefinitions); ::rtl::OUString sIndexName,sTemp; dbtools::composeTableName(m_pTable->getMetaData(),sTemp,aSchema,aName,sIndexName,sal_True,::dbtools::eInIndexDefinitions,sal_True,sal_True); aSql += sIndexName + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ON ")) + aComposedName; Reference< XStatement > xStmt = m_pTable->getConnection()->createStatement( ); if ( xStmt.is() ) { xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); } } } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ETables.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: rt $ $Date: 2005-09-08 06:01:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CONNECTIVITY_FLAT_TABLES_HXX_ #include "flat/ETables.hxx" #endif #ifndef _CONNECTIVITY_FLAT_TABLE_HXX_ #include "flat/ETable.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_ #include <com/sun/star/sdbc/ColumnValue.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_ #include <com/sun/star/sdbc/KeyRule.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_ #include <com/sun/star/sdbcx/KeyType.hpp> #endif #ifndef _CONNECTIVITY_FILE_CATALOG_HXX_ #include "file/FCatalog.hxx" #endif #ifndef _CONNECTIVITY_FILE_OCONNECTION_HXX_ #include "file/FConnection.hxx" #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif using namespace connectivity; using namespace ::comphelper; using namespace connectivity::flat; using namespace connectivity::file; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::container; namespace starutil = ::com::sun::star::util; sdbcx::ObjectType OFlatTables::createObject(const ::rtl::OUString& _rName) { OFlatTable* pRet = new OFlatTable(this,(OFlatConnection*)static_cast<OFileCatalog&>(m_rParent).getConnection(), _rName,::rtl::OUString::createFromAscii("TABLE")); sdbcx::ObjectType xRet = pRet; pRet->construct(); return xRet; } // ------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS pchfix02 (1.13.166); FILE MERGED 2006/09/01 17:22:14 kaib 1.13.166.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ETables.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: obo $ $Date: 2006-09-17 02:39:15 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #ifndef _CONNECTIVITY_FLAT_TABLES_HXX_ #include "flat/ETables.hxx" #endif #ifndef _CONNECTIVITY_FLAT_TABLE_HXX_ #include "flat/ETable.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_ #include <com/sun/star/sdbc/ColumnValue.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_ #include <com/sun/star/sdbc/KeyRule.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_ #include <com/sun/star/sdbcx/KeyType.hpp> #endif #ifndef _CONNECTIVITY_FILE_CATALOG_HXX_ #include "file/FCatalog.hxx" #endif #ifndef _CONNECTIVITY_FILE_OCONNECTION_HXX_ #include "file/FConnection.hxx" #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif using namespace connectivity; using namespace ::comphelper; using namespace connectivity::flat; using namespace connectivity::file; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::container; namespace starutil = ::com::sun::star::util; sdbcx::ObjectType OFlatTables::createObject(const ::rtl::OUString& _rName) { OFlatTable* pRet = new OFlatTable(this,(OFlatConnection*)static_cast<OFileCatalog&>(m_rParent).getConnection(), _rName,::rtl::OUString::createFromAscii("TABLE")); sdbcx::ObjectType xRet = pRet; pRet->construct(); return xRet; } // ------------------------------------------------------------------------- <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/gpu/gpu_data_manager_impl.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/stringprintf.h" #include "base/sys_info.h" #include "base/values.h" #include "base/version.h" #include "content/browser/gpu/gpu_process_host.h" #include "content/common/gpu/gpu_messages.h" #include "content/gpu/gpu_info_collector.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/gpu_data_manager_observer.h" #include "content/public/common/content_client.h" #include "content/public/common/content_switches.h" #include "ui/base/ui_base_switches.h" #include "ui/gl/gl_implementation.h" #include "ui/gl/gl_switches.h" #include "webkit/plugins/plugin_switches.h" using content::BrowserThread; using content::GpuDataManagerObserver; using content::GpuFeatureType; // static content::GpuDataManager* content::GpuDataManager::GetInstance() { return GpuDataManagerImpl::GetInstance(); } // static GpuDataManagerImpl* GpuDataManagerImpl::GetInstance() { return Singleton<GpuDataManagerImpl>::get(); } GpuDataManagerImpl::GpuDataManagerImpl() : complete_gpu_info_already_requested_(false), complete_gpu_info_available_(false), gpu_feature_type_(content::GPU_FEATURE_TYPE_UNKNOWN), preliminary_gpu_feature_type_(content::GPU_FEATURE_TYPE_UNKNOWN), observer_list_(new GpuDataManagerObserverList), software_rendering_(false), card_blacklisted_(false) { Initialize(); } void GpuDataManagerImpl::Initialize() { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kDisableAcceleratedCompositing)) { command_line->AppendSwitch(switches::kDisableAccelerated2dCanvas); command_line->AppendSwitch(switches::kDisableAcceleratedLayers); } if (!command_line->HasSwitch(switches::kSkipGpuDataLoading)) { content::GPUInfo gpu_info; gpu_info_collector::CollectPreliminaryGraphicsInfo(&gpu_info); { base::AutoLock auto_lock(gpu_info_lock_); gpu_info_ = gpu_info; } } if (command_line->HasSwitch(switches::kDisableGpu)) BlacklistCard(); } GpuDataManagerImpl::~GpuDataManagerImpl() { } void GpuDataManagerImpl::RequestCompleteGpuInfoIfNeeded() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (complete_gpu_info_already_requested_ || complete_gpu_info_available_) return; complete_gpu_info_already_requested_ = true; GpuProcessHost::SendOnIO( GpuProcessHost::GPU_PROCESS_KIND_UNSANDBOXED, content::CAUSE_FOR_GPU_LAUNCH_GPUDATAMANAGER_REQUESTCOMPLETEGPUINFOIFNEEDED, new GpuMsg_CollectGraphicsInfo()); } bool GpuDataManagerImpl::IsCompleteGPUInfoAvailable() const { return complete_gpu_info_available_; } void GpuDataManagerImpl::UpdateGpuInfo(const content::GPUInfo& gpu_info) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); { base::AutoLock auto_lock(gpu_info_lock_); #if defined(ARCH_CPU_X86_FAMILY) if (!gpu_info.gpu.vendor_id || !gpu_info.gpu.device_id) gpu_info_.finalized = true; else #endif gpu_info_ = gpu_info; complete_gpu_info_available_ = complete_gpu_info_available_ || gpu_info_.finalized; complete_gpu_info_already_requested_ = complete_gpu_info_already_requested_ || gpu_info_.finalized; content::GetContentClient()->SetGpuInfo(gpu_info_); } // We have to update GpuFeatureType before notify all the observers. NotifyGpuInfoUpdate(); } content::GPUInfo GpuDataManagerImpl::GetGPUInfo() const { return gpu_info_; } void GpuDataManagerImpl::AddLogMessage(Value* msg) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); log_messages_.Append(msg); } GpuFeatureType GpuDataManagerImpl::GetGpuFeatureType() { if (software_rendering_) { GpuFeatureType flags; // Skia's software rendering is probably more efficient than going through // software emulation of the GPU, so use that. flags = content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS; return flags; } return gpu_feature_type_; } bool GpuDataManagerImpl::GpuAccessAllowed() { if (software_rendering_) return true; if (!gpu_info_.gpu_accessible) return false; if (card_blacklisted_) return false; // We only need to block GPU process if more features are disallowed other // than those in the preliminary gpu feature flags because the latter work // through renderer commandline switches. uint32 mask = ~(preliminary_gpu_feature_type_); return (gpu_feature_type_ & mask) == 0; } void GpuDataManagerImpl::AddObserver(GpuDataManagerObserver* observer) { observer_list_->AddObserver(observer); } void GpuDataManagerImpl::RemoveObserver(GpuDataManagerObserver* observer) { observer_list_->RemoveObserver(observer); } void GpuDataManagerImpl::AppendRendererCommandLine( CommandLine* command_line) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(command_line); uint32 flags = GetGpuFeatureType(); if ((flags & content::GPU_FEATURE_TYPE_WEBGL)) { if (!command_line->HasSwitch(switches::kDisableExperimentalWebGL)) command_line->AppendSwitch(switches::kDisableExperimentalWebGL); if (!command_line->HasSwitch(switches::kDisablePepper3dForUntrustedUse)) command_line->AppendSwitch(switches::kDisablePepper3dForUntrustedUse); } if ((flags & content::GPU_FEATURE_TYPE_MULTISAMPLING) && !command_line->HasSwitch(switches::kDisableGLMultisampling)) command_line->AppendSwitch(switches::kDisableGLMultisampling); if ((flags & content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING) && !command_line->HasSwitch(switches::kDisableAcceleratedCompositing)) command_line->AppendSwitch(switches::kDisableAcceleratedCompositing); if ((flags & content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS) && !command_line->HasSwitch(switches::kDisableAccelerated2dCanvas)) command_line->AppendSwitch(switches::kDisableAccelerated2dCanvas); } void GpuDataManagerImpl::AppendGpuCommandLine( CommandLine* command_line) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(command_line); std::string use_gl = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switches::kUseGL); FilePath swiftshader_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath( switches::kSwiftShaderPath); uint32 flags = GetGpuFeatureType(); if ((flags & content::GPU_FEATURE_TYPE_MULTISAMPLING) && !command_line->HasSwitch(switches::kDisableGLMultisampling)) command_line->AppendSwitch(switches::kDisableGLMultisampling); if (software_rendering_) { command_line->AppendSwitchASCII(switches::kUseGL, "swiftshader"); if (swiftshader_path.empty()) swiftshader_path = swiftshader_path_; } else if ((flags & (content::GPU_FEATURE_TYPE_WEBGL | content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING | content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)) && (use_gl == "any")) { command_line->AppendSwitchASCII( switches::kUseGL, gfx::kGLImplementationOSMesaName); } else if (!use_gl.empty()) { command_line->AppendSwitchASCII(switches::kUseGL, use_gl); } if (!swiftshader_path.empty()) command_line->AppendSwitchPath(switches::kSwiftShaderPath, swiftshader_path); { base::AutoLock auto_lock(gpu_info_lock_); if (gpu_info_.optimus) command_line->AppendSwitch(switches::kReduceGpuSandbox); if (gpu_info_.amd_switchable) { // The image transport surface currently doesn't work with AMD Dynamic // Switchable graphics. command_line->AppendSwitch(switches::kReduceGpuSandbox); command_line->AppendSwitch(switches::kDisableImageTransportSurface); } // Pass GPU and driver information to GPU process. We try to avoid full GPU // info collection at GPU process startup, but we need gpu vendor_id, // device_id, driver_vendor, driver_version for deciding whether we need to // collect full info (on Linux) and for crash reporting purpose. command_line->AppendSwitchASCII(switches::kGpuVendorID, base::StringPrintf("0x%04x", gpu_info_.gpu.vendor_id)); command_line->AppendSwitchASCII(switches::kGpuDeviceID, base::StringPrintf("0x%04x", gpu_info_.gpu.device_id)); command_line->AppendSwitchASCII(switches::kGpuDriverVendor, gpu_info_.driver_vendor); command_line->AppendSwitchASCII(switches::kGpuDriverVersion, gpu_info_.driver_version); } } void GpuDataManagerImpl::AppendPluginCommandLine( CommandLine* command_line) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(command_line); #if defined(OS_MACOSX) uint32 flags = GetGpuFeatureType(); // TODO(jbauman): Add proper blacklist support for core animation plugins so // special-casing this video card won't be necessary. See // http://crbug.com/134015 if ((flags & content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING) || (gpu_info_.gpu.vendor_id == 0x8086 && gpu_info_.gpu.device_id == 0x0166) || CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAcceleratedCompositing)) { if (!command_line->HasSwitch( switches::kDisableCoreAnimationPlugins)) command_line->AppendSwitch( switches::kDisableCoreAnimationPlugins); } #endif } void GpuDataManagerImpl::SetGpuFeatureType(GpuFeatureType feature_type) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); UpdateGpuFeatureType(feature_type); preliminary_gpu_feature_type_ = gpu_feature_type_; } void GpuDataManagerImpl::NotifyGpuInfoUpdate() { observer_list_->Notify(&GpuDataManagerObserver::OnGpuInfoUpdate); } void GpuDataManagerImpl::UpdateGpuFeatureType( GpuFeatureType embedder_feature_type) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CommandLine* command_line = CommandLine::ForCurrentProcess(); int flags = embedder_feature_type; // Force disable using the GPU for these features, even if they would // otherwise be allowed. if (card_blacklisted_ || command_line->HasSwitch(switches::kBlacklistAcceleratedCompositing)) { flags |= content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING; } if (card_blacklisted_ || command_line->HasSwitch(switches::kBlacklistWebGL)) { flags |= content::GPU_FEATURE_TYPE_WEBGL; } gpu_feature_type_ = static_cast<GpuFeatureType>(flags); EnableSoftwareRenderingIfNecessary(); } void GpuDataManagerImpl::RegisterSwiftShaderPath(const FilePath& path) { swiftshader_path_ = path; EnableSoftwareRenderingIfNecessary(); } const base::ListValue& GpuDataManagerImpl::GetLogMessages() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return log_messages_; } void GpuDataManagerImpl::EnableSoftwareRenderingIfNecessary() { if (!GpuAccessAllowed() || (gpu_feature_type_ & content::GPU_FEATURE_TYPE_WEBGL)) { #if defined(ENABLE_SWIFTSHADER) if (!swiftshader_path_.empty() && !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableSoftwareRasterizer)) software_rendering_ = true; #endif } } bool GpuDataManagerImpl::ShouldUseSoftwareRendering() { return software_rendering_; } void GpuDataManagerImpl::BlacklistCard() { card_blacklisted_ = true; gpu_feature_type_ = content::GPU_FEATURE_TYPE_ALL; EnableSoftwareRenderingIfNecessary(); NotifyGpuInfoUpdate(); } <commit_msg>Also blacklist Core Animation on Macbook Pros.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/gpu/gpu_data_manager_impl.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/stringprintf.h" #include "base/sys_info.h" #include "base/values.h" #include "base/version.h" #include "content/browser/gpu/gpu_process_host.h" #include "content/common/gpu/gpu_messages.h" #include "content/gpu/gpu_info_collector.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/gpu_data_manager_observer.h" #include "content/public/common/content_client.h" #include "content/public/common/content_switches.h" #include "ui/base/ui_base_switches.h" #include "ui/gl/gl_implementation.h" #include "ui/gl/gl_switches.h" #include "webkit/plugins/plugin_switches.h" using content::BrowserThread; using content::GpuDataManagerObserver; using content::GpuFeatureType; // static content::GpuDataManager* content::GpuDataManager::GetInstance() { return GpuDataManagerImpl::GetInstance(); } // static GpuDataManagerImpl* GpuDataManagerImpl::GetInstance() { return Singleton<GpuDataManagerImpl>::get(); } GpuDataManagerImpl::GpuDataManagerImpl() : complete_gpu_info_already_requested_(false), complete_gpu_info_available_(false), gpu_feature_type_(content::GPU_FEATURE_TYPE_UNKNOWN), preliminary_gpu_feature_type_(content::GPU_FEATURE_TYPE_UNKNOWN), observer_list_(new GpuDataManagerObserverList), software_rendering_(false), card_blacklisted_(false) { Initialize(); } void GpuDataManagerImpl::Initialize() { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kDisableAcceleratedCompositing)) { command_line->AppendSwitch(switches::kDisableAccelerated2dCanvas); command_line->AppendSwitch(switches::kDisableAcceleratedLayers); } if (!command_line->HasSwitch(switches::kSkipGpuDataLoading)) { content::GPUInfo gpu_info; gpu_info_collector::CollectPreliminaryGraphicsInfo(&gpu_info); { base::AutoLock auto_lock(gpu_info_lock_); gpu_info_ = gpu_info; } } if (command_line->HasSwitch(switches::kDisableGpu)) BlacklistCard(); } GpuDataManagerImpl::~GpuDataManagerImpl() { } void GpuDataManagerImpl::RequestCompleteGpuInfoIfNeeded() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (complete_gpu_info_already_requested_ || complete_gpu_info_available_) return; complete_gpu_info_already_requested_ = true; GpuProcessHost::SendOnIO( GpuProcessHost::GPU_PROCESS_KIND_UNSANDBOXED, content::CAUSE_FOR_GPU_LAUNCH_GPUDATAMANAGER_REQUESTCOMPLETEGPUINFOIFNEEDED, new GpuMsg_CollectGraphicsInfo()); } bool GpuDataManagerImpl::IsCompleteGPUInfoAvailable() const { return complete_gpu_info_available_; } void GpuDataManagerImpl::UpdateGpuInfo(const content::GPUInfo& gpu_info) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); { base::AutoLock auto_lock(gpu_info_lock_); #if defined(ARCH_CPU_X86_FAMILY) if (!gpu_info.gpu.vendor_id || !gpu_info.gpu.device_id) gpu_info_.finalized = true; else #endif gpu_info_ = gpu_info; complete_gpu_info_available_ = complete_gpu_info_available_ || gpu_info_.finalized; complete_gpu_info_already_requested_ = complete_gpu_info_already_requested_ || gpu_info_.finalized; content::GetContentClient()->SetGpuInfo(gpu_info_); } // We have to update GpuFeatureType before notify all the observers. NotifyGpuInfoUpdate(); } content::GPUInfo GpuDataManagerImpl::GetGPUInfo() const { return gpu_info_; } void GpuDataManagerImpl::AddLogMessage(Value* msg) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); log_messages_.Append(msg); } GpuFeatureType GpuDataManagerImpl::GetGpuFeatureType() { if (software_rendering_) { GpuFeatureType flags; // Skia's software rendering is probably more efficient than going through // software emulation of the GPU, so use that. flags = content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS; return flags; } return gpu_feature_type_; } bool GpuDataManagerImpl::GpuAccessAllowed() { if (software_rendering_) return true; if (!gpu_info_.gpu_accessible) return false; if (card_blacklisted_) return false; // We only need to block GPU process if more features are disallowed other // than those in the preliminary gpu feature flags because the latter work // through renderer commandline switches. uint32 mask = ~(preliminary_gpu_feature_type_); return (gpu_feature_type_ & mask) == 0; } void GpuDataManagerImpl::AddObserver(GpuDataManagerObserver* observer) { observer_list_->AddObserver(observer); } void GpuDataManagerImpl::RemoveObserver(GpuDataManagerObserver* observer) { observer_list_->RemoveObserver(observer); } void GpuDataManagerImpl::AppendRendererCommandLine( CommandLine* command_line) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(command_line); uint32 flags = GetGpuFeatureType(); if ((flags & content::GPU_FEATURE_TYPE_WEBGL)) { if (!command_line->HasSwitch(switches::kDisableExperimentalWebGL)) command_line->AppendSwitch(switches::kDisableExperimentalWebGL); if (!command_line->HasSwitch(switches::kDisablePepper3dForUntrustedUse)) command_line->AppendSwitch(switches::kDisablePepper3dForUntrustedUse); } if ((flags & content::GPU_FEATURE_TYPE_MULTISAMPLING) && !command_line->HasSwitch(switches::kDisableGLMultisampling)) command_line->AppendSwitch(switches::kDisableGLMultisampling); if ((flags & content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING) && !command_line->HasSwitch(switches::kDisableAcceleratedCompositing)) command_line->AppendSwitch(switches::kDisableAcceleratedCompositing); if ((flags & content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS) && !command_line->HasSwitch(switches::kDisableAccelerated2dCanvas)) command_line->AppendSwitch(switches::kDisableAccelerated2dCanvas); } void GpuDataManagerImpl::AppendGpuCommandLine( CommandLine* command_line) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(command_line); std::string use_gl = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switches::kUseGL); FilePath swiftshader_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath( switches::kSwiftShaderPath); uint32 flags = GetGpuFeatureType(); if ((flags & content::GPU_FEATURE_TYPE_MULTISAMPLING) && !command_line->HasSwitch(switches::kDisableGLMultisampling)) command_line->AppendSwitch(switches::kDisableGLMultisampling); if (software_rendering_) { command_line->AppendSwitchASCII(switches::kUseGL, "swiftshader"); if (swiftshader_path.empty()) swiftshader_path = swiftshader_path_; } else if ((flags & (content::GPU_FEATURE_TYPE_WEBGL | content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING | content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)) && (use_gl == "any")) { command_line->AppendSwitchASCII( switches::kUseGL, gfx::kGLImplementationOSMesaName); } else if (!use_gl.empty()) { command_line->AppendSwitchASCII(switches::kUseGL, use_gl); } if (!swiftshader_path.empty()) command_line->AppendSwitchPath(switches::kSwiftShaderPath, swiftshader_path); { base::AutoLock auto_lock(gpu_info_lock_); if (gpu_info_.optimus) command_line->AppendSwitch(switches::kReduceGpuSandbox); if (gpu_info_.amd_switchable) { // The image transport surface currently doesn't work with AMD Dynamic // Switchable graphics. command_line->AppendSwitch(switches::kReduceGpuSandbox); command_line->AppendSwitch(switches::kDisableImageTransportSurface); } // Pass GPU and driver information to GPU process. We try to avoid full GPU // info collection at GPU process startup, but we need gpu vendor_id, // device_id, driver_vendor, driver_version for deciding whether we need to // collect full info (on Linux) and for crash reporting purpose. command_line->AppendSwitchASCII(switches::kGpuVendorID, base::StringPrintf("0x%04x", gpu_info_.gpu.vendor_id)); command_line->AppendSwitchASCII(switches::kGpuDeviceID, base::StringPrintf("0x%04x", gpu_info_.gpu.device_id)); command_line->AppendSwitchASCII(switches::kGpuDriverVendor, gpu_info_.driver_vendor); command_line->AppendSwitchASCII(switches::kGpuDriverVersion, gpu_info_.driver_version); } } void GpuDataManagerImpl::AppendPluginCommandLine( CommandLine* command_line) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(command_line); #if defined(OS_MACOSX) uint32 flags = GetGpuFeatureType(); // TODO(jbauman): Add proper blacklist support for core animation plugins so // special-casing this video card won't be necessary. See // http://crbug.com/134015 if ((flags & content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING) || (gpu_info_.gpu.vendor_id == 0x8086 && // Intel gpu_info_.gpu.device_id == 0x0166) || // HD 4000 (gpu_info_.gpu.vendor_id == 0x10de && // NVidia gpu_info_.gpu.device_id == 0x0fd5) || // GeForce GT 650M CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAcceleratedCompositing)) { if (!command_line->HasSwitch( switches::kDisableCoreAnimationPlugins)) command_line->AppendSwitch( switches::kDisableCoreAnimationPlugins); } #endif } void GpuDataManagerImpl::SetGpuFeatureType(GpuFeatureType feature_type) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); UpdateGpuFeatureType(feature_type); preliminary_gpu_feature_type_ = gpu_feature_type_; } void GpuDataManagerImpl::NotifyGpuInfoUpdate() { observer_list_->Notify(&GpuDataManagerObserver::OnGpuInfoUpdate); } void GpuDataManagerImpl::UpdateGpuFeatureType( GpuFeatureType embedder_feature_type) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CommandLine* command_line = CommandLine::ForCurrentProcess(); int flags = embedder_feature_type; // Force disable using the GPU for these features, even if they would // otherwise be allowed. if (card_blacklisted_ || command_line->HasSwitch(switches::kBlacklistAcceleratedCompositing)) { flags |= content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING; } if (card_blacklisted_ || command_line->HasSwitch(switches::kBlacklistWebGL)) { flags |= content::GPU_FEATURE_TYPE_WEBGL; } gpu_feature_type_ = static_cast<GpuFeatureType>(flags); EnableSoftwareRenderingIfNecessary(); } void GpuDataManagerImpl::RegisterSwiftShaderPath(const FilePath& path) { swiftshader_path_ = path; EnableSoftwareRenderingIfNecessary(); } const base::ListValue& GpuDataManagerImpl::GetLogMessages() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return log_messages_; } void GpuDataManagerImpl::EnableSoftwareRenderingIfNecessary() { if (!GpuAccessAllowed() || (gpu_feature_type_ & content::GPU_FEATURE_TYPE_WEBGL)) { #if defined(ENABLE_SWIFTSHADER) if (!swiftshader_path_.empty() && !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableSoftwareRasterizer)) software_rendering_ = true; #endif } } bool GpuDataManagerImpl::ShouldUseSoftwareRendering() { return software_rendering_; } void GpuDataManagerImpl::BlacklistCard() { card_blacklisted_ = true; gpu_feature_type_ = content::GPU_FEATURE_TYPE_ALL; EnableSoftwareRenderingIfNecessary(); NotifyGpuInfoUpdate(); } <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2019, Mike Dunston * 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. * * \file Can.hxx * * ESP32 adapter code using the WiFiClient provided by the WiFiServer code * for interfacing with the OpenMRN stack. * * @author Mike Dunston * @date 13 January 2019 */ // This include is exclusive against freertos_drivers/arduino/Esp32WiFiClientAdapter.hxx #ifndef _FREERTOS_DRIVERS_ARDUINO_ESP32WIFI_HXX_ #define _FREERTOS_DRIVERS_ARDUINO_ESP32WIFI_HXX_ #include <Arduino.h> #include <WiFi.h> class Esp32WiFiClientAdapter { public: WiFiClientAdapter(WiFiClient client) : client_(client){ client_.setNoDelay(true); } // on the ESP32 there is no TX limit method size_t availableForWrite() { return client_.connected(); } size_t write(const char *buffer, size_t len) { if(client_.connected()) { return client_.write(buffer, len); } return 0; } size_t available() { if(client_.connected()) { return client_.available(); } return 0; } size_t read(const char *buffer, size_t len) { size_t bytesRead = 0; if(client_.connected()) { bytesRead = client_.read((uint8_t *)buffer, len); } return bytesRead; } private: WiFiClient client_; }; #endif /* _FREERTOS_DRIVERS_ARDUINO_ESP32WIFI_HXX_ */<commit_msg>fix constructor name<commit_after>/** \copyright * Copyright (c) 2019, Mike Dunston * 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. * * \file Can.hxx * * ESP32 adapter code using the WiFiClient provided by the WiFiServer code * for interfacing with the OpenMRN stack. * * @author Mike Dunston * @date 13 January 2019 */ // This include is exclusive against freertos_drivers/arduino/Esp32WiFiClientAdapter.hxx #ifndef _FREERTOS_DRIVERS_ARDUINO_ESP32WIFI_HXX_ #define _FREERTOS_DRIVERS_ARDUINO_ESP32WIFI_HXX_ #include <Arduino.h> #include <WiFi.h> class Esp32WiFiClientAdapter { public: Esp32WiFiClientAdapter(WiFiClient client) : client_(client){ client_.setNoDelay(true); } // on the ESP32 there is no TX limit method size_t availableForWrite() { return client_.connected(); } size_t write(const char *buffer, size_t len) { if(client_.connected()) { return client_.write(buffer, len); } return 0; } size_t available() { if(client_.connected()) { return client_.available(); } return 0; } size_t read(const char *buffer, size_t len) { size_t bytesRead = 0; if(client_.connected()) { bytesRead = client_.read((uint8_t *)buffer, len); } return bytesRead; } private: WiFiClient client_; }; #endif /* _FREERTOS_DRIVERS_ARDUINO_ESP32WIFI_HXX_ */<|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Tests for CppBoundClass, in conjunction with CppBindingExample. Binds // a CppBindingExample class into JavaScript in a custom test shell and tests // the binding from the outside by loading JS into the shell. #include "base/strings/utf_string_conversions.h" #include "content/public/renderer/render_view_observer.h" #include "content/public/test/render_view_test.h" #include "third_party/WebKit/public/platform/WebURLRequest.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebElement.h" #include "webkit/renderer/cpp_binding_example.h" using webkit_glue::CppArgumentList; using webkit_glue::CppBindingExample; using webkit_glue::CppVariant; namespace content { class CppBindingExampleSubObject : public CppBindingExample { public: CppBindingExampleSubObject() { sub_value_.Set("sub!"); BindProperty("sub_value", &sub_value_); } private: CppVariant sub_value_; }; class CppBindingExampleWithOptionalFallback : public CppBindingExample { public: CppBindingExampleWithOptionalFallback() { BindProperty("sub_object", sub_object_.GetAsCppVariant()); } void set_fallback_method_enabled(bool state) { BindFallbackCallback(state ? base::Bind(&CppBindingExampleWithOptionalFallback::fallbackMethod, base::Unretained(this)) : CppBoundClass::Callback()); } // The fallback method does nothing, but because of it the JavaScript keeps // running when a nonexistent method is called on an object. void fallbackMethod(const CppArgumentList& args, CppVariant* result) { } private: CppBindingExampleSubObject sub_object_; }; class TestObserver : public RenderViewObserver { public: explicit TestObserver(RenderView* render_view) : RenderViewObserver(render_view) {} virtual void DidClearWindowObject(WebKit::WebFrame* frame) OVERRIDE { example_bound_class_.BindToJavascript(frame, "example"); } void set_fallback_method_enabled(bool use_fallback) { example_bound_class_.set_fallback_method_enabled(use_fallback); } private: CppBindingExampleWithOptionalFallback example_bound_class_; }; class CppBoundClassTest : public RenderViewTest { public: CppBoundClassTest() {} virtual void SetUp() OVERRIDE { RenderViewTest::SetUp(); observer_.reset(new TestObserver(view_)); observer_->set_fallback_method_enabled(useFallback()); WebKit::WebURLRequest url_request; url_request.initialize(); url_request.setURL(GURL("about:blank")); GetMainFrame()->loadRequest(url_request); ProcessPendingMessages(); } // Executes the specified JavaScript and checks that the resulting document // text is empty. void CheckJavaScriptFailure(const std::string& javascript) { ExecuteJavaScript(javascript.c_str()); EXPECT_EQ( "", UTF16ToASCII(GetMainFrame()->document().documentElement().innerText())); } void CheckTrue(const std::string& expression) { int was_page_a = -1; string16 check_page_a = ASCIIToUTF16(std::string("Number(") + expression + ")"); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(check_page_a, &was_page_a)); EXPECT_EQ(1, was_page_a); } protected: virtual bool useFallback() { return false; } private: scoped_ptr<TestObserver> observer_; }; class CppBoundClassWithFallbackMethodTest : public CppBoundClassTest { protected: virtual bool useFallback() OVERRIDE { return true; } }; // Ensures that the example object has been bound to JS. TEST_F(CppBoundClassTest, ObjectExists) { CheckTrue("typeof window.example == 'object'"); // An additional check to test our test. CheckTrue("typeof window.invalid_object == 'undefined'"); } TEST_F(CppBoundClassTest, PropertiesAreInitialized) { CheckTrue("example.my_value == 10"); CheckTrue("example.my_other_value == 'Reinitialized!'"); } TEST_F(CppBoundClassTest, SubOject) { CheckTrue("typeof window.example.sub_object == 'object'"); CheckTrue("example.sub_object.sub_value == 'sub!'"); } TEST_F(CppBoundClassTest, SetAndGetProperties) { // The property on the left will be set to the value on the right, then // checked to make sure it holds that same value. static const std::string tests[] = { "example.my_value", "7", "example.my_value", "'test'", "example.my_other_value", "3.14", "example.my_other_value", "false", "" // Array end marker: insert additional test pairs before this. }; for (int i = 0; tests[i] != ""; i += 2) { std::string left = tests[i]; std::string right = tests[i + 1]; // left = right; std::string js = left; js.append(" = "); js.append(right); js.append(";"); ExecuteJavaScript(js.c_str()); std::string expression = left; expression += " == "; expression += right; CheckTrue(expression); } } TEST_F(CppBoundClassTest, SetAndGetPropertiesWithCallbacks) { // TODO(dglazkov): fix NPObject issues around failing property setters and // getters and add tests for situations when GetProperty or SetProperty fail. ExecuteJavaScript("example.my_value_with_callback = 10;"); CheckTrue("example.my_value_with_callback == 10"); ExecuteJavaScript("example.my_value_with_callback = 11;"); CheckTrue("example.my_value_with_callback == 11"); CheckTrue("example.same == 42"); ExecuteJavaScript("example.same = 24;"); CheckTrue("example.same == 42"); } TEST_F(CppBoundClassTest, InvokeMethods) { // The expression on the left is expected to return the value on the right. static const std::string tests[] = { "example.echoValue(true) == true", "example.echoValue(13) == 13", "example.echoValue(2.718) == 2.718", "example.echoValue('yes') == 'yes'", "example.echoValue() == null", // Too few arguments "example.echoType(false) == true", "example.echoType(19) == 3.14159", "example.echoType(9.876) == 3.14159", "example.echoType('test string') == 'Success!'", "example.echoType() == null", // Too few arguments // Comparing floats that aren't integer-valued is usually problematic due // to rounding, but exact powers of 2 should also be safe. "example.plus(2.5, 18.0) == 20.5", "example.plus(2, 3.25) == 5.25", "example.plus(2, 3) == 5", "example.plus() == null", // Too few arguments "example.plus(1) == null", // Too few arguments "example.plus(1, 'test') == null", // Wrong argument type "example.plus('test', 2) == null", // Wrong argument type "example.plus('one', 'two') == null", // Wrong argument type "" // Array end marker: insert additional test pairs before this. }; for (int i = 0; tests[i] != ""; i++) CheckTrue(tests[i]); ExecuteJavaScript("example.my_value = 3.25; example.my_other_value = 1.25;"); CheckTrue("example.plus(example.my_value, example.my_other_value) == 4.5"); } // Tests that invoking a nonexistent method with no fallback method stops the // script's execution TEST_F(CppBoundClassTest, InvokeNonexistentMethodNoFallback) { std::string js = "example.nonExistentMethod();document.writeln('SUCCESS');"; CheckJavaScriptFailure(js); } // Ensures existent methods can be invoked successfully when the fallback method // is used TEST_F(CppBoundClassWithFallbackMethodTest, InvokeExistentMethodsWithFallback) { CheckTrue("example.echoValue(34) == 34"); } } // namespace content <commit_msg>Delete CppBound class after the test ends.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Tests for CppBoundClass, in conjunction with CppBindingExample. Binds // a CppBindingExample class into JavaScript in a custom test shell and tests // the binding from the outside by loading JS into the shell. #include "base/strings/utf_string_conversions.h" #include "content/public/renderer/render_view_observer.h" #include "content/public/test/render_view_test.h" #include "third_party/WebKit/public/platform/WebURLRequest.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebElement.h" #include "webkit/renderer/cpp_binding_example.h" using webkit_glue::CppArgumentList; using webkit_glue::CppBindingExample; using webkit_glue::CppVariant; namespace content { class CppBindingExampleSubObject : public CppBindingExample { public: CppBindingExampleSubObject() { sub_value_.Set("sub!"); BindProperty("sub_value", &sub_value_); } private: CppVariant sub_value_; }; class CppBindingExampleWithOptionalFallback : public CppBindingExample { public: CppBindingExampleWithOptionalFallback() { BindProperty("sub_object", sub_object_.GetAsCppVariant()); } void set_fallback_method_enabled(bool state) { BindFallbackCallback(state ? base::Bind(&CppBindingExampleWithOptionalFallback::fallbackMethod, base::Unretained(this)) : CppBoundClass::Callback()); } // The fallback method does nothing, but because of it the JavaScript keeps // running when a nonexistent method is called on an object. void fallbackMethod(const CppArgumentList& args, CppVariant* result) { } private: CppBindingExampleSubObject sub_object_; }; class TestObserver : public RenderViewObserver { public: explicit TestObserver(RenderView* render_view) : RenderViewObserver(render_view) {} virtual void DidClearWindowObject(WebKit::WebFrame* frame) OVERRIDE { example_bound_class_.BindToJavascript(frame, "example"); } void set_fallback_method_enabled(bool use_fallback) { example_bound_class_.set_fallback_method_enabled(use_fallback); } private: CppBindingExampleWithOptionalFallback example_bound_class_; }; class CppBoundClassTest : public RenderViewTest { public: CppBoundClassTest() {} virtual void SetUp() OVERRIDE { RenderViewTest::SetUp(); observer_.reset(new TestObserver(view_)); observer_->set_fallback_method_enabled(useFallback()); WebKit::WebURLRequest url_request; url_request.initialize(); url_request.setURL(GURL("about:blank")); GetMainFrame()->loadRequest(url_request); ProcessPendingMessages(); } virtual void TearDown() OVERRIDE { observer_.reset(); RenderViewTest::TearDown(); } // Executes the specified JavaScript and checks that the resulting document // text is empty. void CheckJavaScriptFailure(const std::string& javascript) { ExecuteJavaScript(javascript.c_str()); EXPECT_EQ( "", UTF16ToASCII(GetMainFrame()->document().documentElement().innerText())); } void CheckTrue(const std::string& expression) { int was_page_a = -1; string16 check_page_a = ASCIIToUTF16(std::string("Number(") + expression + ")"); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(check_page_a, &was_page_a)); EXPECT_EQ(1, was_page_a); } protected: virtual bool useFallback() { return false; } private: scoped_ptr<TestObserver> observer_; }; class CppBoundClassWithFallbackMethodTest : public CppBoundClassTest { protected: virtual bool useFallback() OVERRIDE { return true; } }; // Ensures that the example object has been bound to JS. TEST_F(CppBoundClassTest, ObjectExists) { CheckTrue("typeof window.example == 'object'"); // An additional check to test our test. CheckTrue("typeof window.invalid_object == 'undefined'"); } TEST_F(CppBoundClassTest, PropertiesAreInitialized) { CheckTrue("example.my_value == 10"); CheckTrue("example.my_other_value == 'Reinitialized!'"); } TEST_F(CppBoundClassTest, SubOject) { CheckTrue("typeof window.example.sub_object == 'object'"); CheckTrue("example.sub_object.sub_value == 'sub!'"); } TEST_F(CppBoundClassTest, SetAndGetProperties) { // The property on the left will be set to the value on the right, then // checked to make sure it holds that same value. static const std::string tests[] = { "example.my_value", "7", "example.my_value", "'test'", "example.my_other_value", "3.14", "example.my_other_value", "false", "" // Array end marker: insert additional test pairs before this. }; for (int i = 0; tests[i] != ""; i += 2) { std::string left = tests[i]; std::string right = tests[i + 1]; // left = right; std::string js = left; js.append(" = "); js.append(right); js.append(";"); ExecuteJavaScript(js.c_str()); std::string expression = left; expression += " == "; expression += right; CheckTrue(expression); } } TEST_F(CppBoundClassTest, SetAndGetPropertiesWithCallbacks) { // TODO(dglazkov): fix NPObject issues around failing property setters and // getters and add tests for situations when GetProperty or SetProperty fail. ExecuteJavaScript("example.my_value_with_callback = 10;"); CheckTrue("example.my_value_with_callback == 10"); ExecuteJavaScript("example.my_value_with_callback = 11;"); CheckTrue("example.my_value_with_callback == 11"); CheckTrue("example.same == 42"); ExecuteJavaScript("example.same = 24;"); CheckTrue("example.same == 42"); } TEST_F(CppBoundClassTest, InvokeMethods) { // The expression on the left is expected to return the value on the right. static const std::string tests[] = { "example.echoValue(true) == true", "example.echoValue(13) == 13", "example.echoValue(2.718) == 2.718", "example.echoValue('yes') == 'yes'", "example.echoValue() == null", // Too few arguments "example.echoType(false) == true", "example.echoType(19) == 3.14159", "example.echoType(9.876) == 3.14159", "example.echoType('test string') == 'Success!'", "example.echoType() == null", // Too few arguments // Comparing floats that aren't integer-valued is usually problematic due // to rounding, but exact powers of 2 should also be safe. "example.plus(2.5, 18.0) == 20.5", "example.plus(2, 3.25) == 5.25", "example.plus(2, 3) == 5", "example.plus() == null", // Too few arguments "example.plus(1) == null", // Too few arguments "example.plus(1, 'test') == null", // Wrong argument type "example.plus('test', 2) == null", // Wrong argument type "example.plus('one', 'two') == null", // Wrong argument type "" // Array end marker: insert additional test pairs before this. }; for (int i = 0; tests[i] != ""; i++) CheckTrue(tests[i]); ExecuteJavaScript("example.my_value = 3.25; example.my_other_value = 1.25;"); CheckTrue("example.plus(example.my_value, example.my_other_value) == 4.5"); } // Tests that invoking a nonexistent method with no fallback method stops the // script's execution TEST_F(CppBoundClassTest, InvokeNonexistentMethodNoFallback) { std::string js = "example.nonExistentMethod();document.writeln('SUCCESS');"; CheckJavaScriptFailure(js); } // Ensures existent methods can be invoked successfully when the fallback method // is used TEST_F(CppBoundClassWithFallbackMethodTest, InvokeExistentMethodsWithFallback) { CheckTrue("example.echoValue(34) == 34"); } } // namespace content <|endoftext|>
<commit_before>/** * \file * \brief ThisThread namespace implementation * * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-02-16 */ #include "distortos/ThisThread.hpp" #include "distortos/scheduler/getScheduler.hpp" #include "distortos/scheduler/Scheduler.hpp" namespace distortos { namespace ThisThread { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ ThreadBase& get() { return scheduler::getScheduler().getCurrentThreadBase(); } uint8_t getEffectivePriority() { return scheduler::getScheduler().getCurrentThreadControlBlock().getEffectivePriority(); } uint8_t getPriority() { return scheduler::getScheduler().getCurrentThreadControlBlock().getPriority(); } void setPriority(const uint8_t priority, const bool alwaysBehind) { scheduler::getScheduler().getCurrentThreadControlBlock().setPriority(priority, alwaysBehind); } void sleepFor(const TickClock::duration duration) { sleepUntil(TickClock::now() + duration + TickClock::duration{1}); } void sleepUntil(const TickClock::time_point timePoint) { scheduler::ThreadControlBlockList sleepingList {scheduler::getScheduler().getThreadControlBlockListAllocator(), scheduler::ThreadControlBlock::State::Sleeping}; scheduler::getScheduler().blockUntil(sleepingList, timePoint); } void yield() { scheduler::getScheduler().yield(); } } // namespace ThisThread } // namespace distortos <commit_msg>ThisThread::sleepUntil(): small optimization<commit_after>/** * \file * \brief ThisThread namespace implementation * * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-02-16 */ #include "distortos/ThisThread.hpp" #include "distortos/scheduler/getScheduler.hpp" #include "distortos/scheduler/Scheduler.hpp" namespace distortos { namespace ThisThread { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ ThreadBase& get() { return scheduler::getScheduler().getCurrentThreadBase(); } uint8_t getEffectivePriority() { return scheduler::getScheduler().getCurrentThreadControlBlock().getEffectivePriority(); } uint8_t getPriority() { return scheduler::getScheduler().getCurrentThreadControlBlock().getPriority(); } void setPriority(const uint8_t priority, const bool alwaysBehind) { scheduler::getScheduler().getCurrentThreadControlBlock().setPriority(priority, alwaysBehind); } void sleepFor(const TickClock::duration duration) { sleepUntil(TickClock::now() + duration + TickClock::duration{1}); } void sleepUntil(const TickClock::time_point timePoint) { auto& scheduler = scheduler::getScheduler(); scheduler::ThreadControlBlockList sleepingList {scheduler.getThreadControlBlockListAllocator(), scheduler::ThreadControlBlock::State::Sleeping}; scheduler.blockUntil(sleepingList, timePoint); } void yield() { scheduler::getScheduler().yield(); } } // namespace ThisThread } // namespace distortos <|endoftext|>
<commit_before>#include "gum/Statistics.h" #include "gum/StatFPS.h" #include "gum/StatTag.h" #include "gum/GUM_GTxt.h" #include <logger.h> #include <glp_loop.h> #include <ps_3d.h> #include <sprite2/pre_defined.h> #include S2_MAT_HEADER #include <sprite2/StatDrawCall.h> #include <sprite2/StatPingPong.h> #include <sprite2/StatTopNodes.h> #include <sprite2/StatSymbol.h> #include <shaderlab/ShaderMgr.h> #include <shaderlab/Statistics.h> #include <shaderlab/StatDrawCall.h> #include <string> #include <time.h> namespace gum { SINGLETON_DEFINITION(Statistics); static const float FPS_SMOOTHING = 0.99f; Statistics::Statistics() : m_flags(0) , m_tpf(0) , m_tpf_smooth(0) , m_no_stat_begin(0) , m_no_stat_tot(0) , m_opt_enable(false) { memset(&m_mem, 0, sizeof(m_mem)); } void Statistics::EnableGraph(bool enable) { if (enable) { m_flags |= FLAG_PRINT_GRAPH; } else { m_flags &= ~FLAG_PRINT_GRAPH; } } void Statistics::EnableConsole(bool enable) { if (enable) { m_flags |= FLAG_PRINT_CONSOLE; } else { m_flags &= ~FLAG_PRINT_CONSOLE; } } void Statistics::EnableFile(bool enable) { if (enable == IsFileEnable()) { return; } if (enable) { m_flags |= FLAG_PRINT_FILE; #ifdef __ANDROID__ m_fout.open("/sdcard/lr_stat.bin", std::ofstream::out | std::ofstream::binary); #else m_fout.open("lr_stat.bin", std::ofstream::out | std::ofstream::binary); #endif // __ANDROID__ } else { m_flags &= ~FLAG_PRINT_FILE; m_fout.close(); } } bool Statistics::IsGraphEnable() const { return (m_flags & FLAG_PRINT_GRAPH) != 0; } bool Statistics::IsConsoleEnable() const { return (m_flags & FLAG_PRINT_CONSOLE) != 0; } bool Statistics::IsFileEnable() const { return (m_flags & FLAG_PRINT_FILE) != 0; } void Statistics::Update() { if (m_flags == 0) { return; } m_tpf = glp_get_dt(); m_tpf_smooth = (m_tpf_smooth * FPS_SMOOTHING) + m_tpf * (1.0f - FPS_SMOOTHING); } void Statistics::Print() { StatTag::Instance()->PrintScreen(); if (m_flags == 0) { return; } if (m_flags & FLAG_PRINT_GRAPH) { PrintScreen(); } if (m_flags & FLAG_PRINT_CONSOLE) { PrintConsole(); } if (m_flags & FLAG_PRINT_FILE) { PrintFile(); } } void Statistics::Reset() { if (m_flags == 0) { return; } m_tpf = 0; sl::Statistics::Instance()->Reset(); sl::StatDrawCall::Instance()->Reset(); s2::StatDrawCall::Instance()->Reset(); s2::StatPingPong::Instance()->Reset(); s2::StatTopNodes::Instance()->Reset(); s2::StatSymbol::Instance()->Reset(); } void Statistics::Flush() { StatTag::Instance()->Flush(); } void Statistics::NoStatBegin() { m_no_stat_begin = glp_get_time(); } void Statistics::NoStatEnd() { m_no_stat_tot = (glp_get_time() - m_no_stat_begin); } void Statistics::OptEnable(bool enable) { m_opt_enable = enable; } void Statistics::SetMem(float tot, float lua) { m_mem.tot = tot; m_mem.lua = lua; } void Statistics::PrintScreen() const { sl::ShaderMgr* mgr = sl::ShaderMgr::Instance(); mgr->SetShader(sl::SPRITE2); static char buf[512]; const int w = 960; const int top = 280; S2_MAT mt; mt.Translate(0, top); sprintf(buf, "OPT: %s, emitter: %d", m_opt_enable ? "open" : "closed", p3d_emitter_count()); GTxt::Instance()->Draw(mt, buf, w); mt.Translate(0, -30); sprintf(buf, "FPS: %.1f, ms: %.1f, ex:%.1f", 1000.0f / m_tpf, m_tpf_smooth, m_no_stat_tot / 1000.0f); GTxt::Instance()->Draw(mt, buf, w); mt.Translate(0, -30); sprintf(buf, "MEM: tot %.1f, tex %.1f, lua %.1f", m_mem.tot, m_mem.tex, m_mem.lua); GTxt::Instance()->Draw(mt, buf, w); static std::string buf_str; buf_str.reserve(512); mt.Translate(0, -30); sl::Statistics::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); mt.Translate(0, -30); s2::StatDrawCall::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); mt.Translate(0, -40); s2::StatPingPong::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); mt.Translate(450, -100); s2::StatTopNodes::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); // mt.Translate(450, 180); // s2::StatSymbol::Instance()->Print(buf_str); // GTxt::Instance()->Draw(mt, buf_str, w); // buf_str.clear(); // mt.Translate(0, -230); // sl::StatDrawCall::Instance()->Print(buf_str); // GTxt::Instance()->Draw(mt, buf_str, w); // buf_str.clear(); mgr->FlushShader(); } void Statistics::PrintConsole() const { static const int PRINT_COUNT = 30; static int count = 0; ++count; if (count == PRINT_COUNT) { count = 0; sl::Statistics* stat = sl::Statistics::Instance(); int dc = stat->GetDrawCall(); int count = stat->GetVertices(); float fps_curr = StatFPS::Instance()->GetFPSCurr(); float curr_cost = 0; if (fps_curr != 0) { curr_cost = 1000.0f / fps_curr; } LOGI("fps %.1f, cost %.1f, dc %d, vertices %d, cost avg %.1f\n", 1000.0f / m_tpf_smooth, m_tpf_smooth, dc, count, curr_cost); } } void Statistics::PrintFile() const { sl::Statistics* sl_stat = sl::Statistics::Instance(); static char buf[512]; sprintf(buf, "timestamp %lu, cost %.1f, vertices %d, dc %d\n", time(NULL), m_tpf_smooth, sl_stat->GetVertices(), sl_stat->GetDrawCall()); m_fout << buf; // static std::string buf_str; // buf_str.reserve(1024); // s2::StatTopNodes::Instance()->Print(buf_str); // m_fout << buf_str; static const int FLUSH_COUNT = 100; static int count = 0; ++count; if (count == FLUSH_COUNT) { count = 0; m_fout.flush(); } } }<commit_msg>[ADDED] obj count to stat<commit_after>#include "gum/Statistics.h" #include "gum/StatFPS.h" #include "gum/StatTag.h" #include "gum/GUM_GTxt.h" #include "gum/SymbolPool.h" #include "gum/Image.h" #include <logger.h> #include <glp_loop.h> #include <ps_3d.h> #include <sprite2/pre_defined.h> #include S2_MAT_HEADER #include <sprite2/StatDrawCall.h> #include <sprite2/StatPingPong.h> #include <sprite2/StatTopNodes.h> #include <sprite2/StatSymbol.h> #include <sprite2/S2_Sprite.h> #include <sprite2/S2_Actor.h> #include <shaderlab/ShaderMgr.h> #include <shaderlab/Statistics.h> #include <shaderlab/StatDrawCall.h> #include <string> #include <time.h> namespace gum { SINGLETON_DEFINITION(Statistics); static const float FPS_SMOOTHING = 0.99f; Statistics::Statistics() : m_flags(0) , m_tpf(0) , m_tpf_smooth(0) , m_no_stat_begin(0) , m_no_stat_tot(0) , m_opt_enable(false) { memset(&m_mem, 0, sizeof(m_mem)); } void Statistics::EnableGraph(bool enable) { if (enable) { m_flags |= FLAG_PRINT_GRAPH; } else { m_flags &= ~FLAG_PRINT_GRAPH; } } void Statistics::EnableConsole(bool enable) { if (enable) { m_flags |= FLAG_PRINT_CONSOLE; } else { m_flags &= ~FLAG_PRINT_CONSOLE; } } void Statistics::EnableFile(bool enable) { if (enable == IsFileEnable()) { return; } if (enable) { m_flags |= FLAG_PRINT_FILE; #ifdef __ANDROID__ m_fout.open("/sdcard/lr_stat.bin", std::ofstream::out | std::ofstream::binary); #else m_fout.open("lr_stat.bin", std::ofstream::out | std::ofstream::binary); #endif // __ANDROID__ } else { m_flags &= ~FLAG_PRINT_FILE; m_fout.close(); } } bool Statistics::IsGraphEnable() const { return (m_flags & FLAG_PRINT_GRAPH) != 0; } bool Statistics::IsConsoleEnable() const { return (m_flags & FLAG_PRINT_CONSOLE) != 0; } bool Statistics::IsFileEnable() const { return (m_flags & FLAG_PRINT_FILE) != 0; } void Statistics::Update() { if (m_flags == 0) { return; } m_tpf = glp_get_dt(); m_tpf_smooth = (m_tpf_smooth * FPS_SMOOTHING) + m_tpf * (1.0f - FPS_SMOOTHING); } void Statistics::Print() { StatTag::Instance()->PrintScreen(); if (m_flags == 0) { return; } if (m_flags & FLAG_PRINT_GRAPH) { PrintScreen(); } if (m_flags & FLAG_PRINT_CONSOLE) { PrintConsole(); } if (m_flags & FLAG_PRINT_FILE) { PrintFile(); } } void Statistics::Reset() { if (m_flags == 0) { return; } m_tpf = 0; sl::Statistics::Instance()->Reset(); sl::StatDrawCall::Instance()->Reset(); s2::StatDrawCall::Instance()->Reset(); s2::StatPingPong::Instance()->Reset(); s2::StatTopNodes::Instance()->Reset(); s2::StatSymbol::Instance()->Reset(); } void Statistics::Flush() { StatTag::Instance()->Flush(); } void Statistics::NoStatBegin() { m_no_stat_begin = glp_get_time(); } void Statistics::NoStatEnd() { m_no_stat_tot = (glp_get_time() - m_no_stat_begin); } void Statistics::OptEnable(bool enable) { m_opt_enable = enable; } void Statistics::SetMem(float tot, float lua) { m_mem.tot = tot; m_mem.lua = lua; } void Statistics::PrintScreen() const { sl::ShaderMgr* mgr = sl::ShaderMgr::Instance(); mgr->SetShader(sl::SPRITE2); static char buf[512]; const int w = 960; const int top = 280; S2_MAT mt; mt.Translate(0, top); sprintf(buf, "OPT: %s, emitter: %d", m_opt_enable ? "open" : "closed", p3d_emitter_count()); GTxt::Instance()->Draw(mt, buf, w); mt.Translate(0, -30); sprintf(buf, "FPS: %.1f, ms: %.1f, ex:%.1f", 1000.0f / m_tpf, m_tpf_smooth, m_no_stat_tot / 1000.0f); GTxt::Instance()->Draw(mt, buf, w); mt.Translate(0, -30); sprintf(buf, "MEM: tot %.1f, tex %.1f, lua %.1f", m_mem.tot, m_mem.tex, m_mem.lua); GTxt::Instance()->Draw(mt, buf, w); static std::string buf_str; buf_str.reserve(512); mt.Translate(0, -30); sl::Statistics::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); mt.Translate(0, -30); s2::StatDrawCall::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); mt.Translate(0, -40); s2::StatPingPong::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); mt.Translate(0, -50); sprintf(buf, "COUNT: sym %d, spr %d, actor %d, img %d", SymbolPool::Instance()->Count(), s2::Sprite::GetAllSprCount(), s2::Actor::GetAllActorCount(), ImageMgr::Instance()->Count()); GTxt::Instance()->Draw(mt, buf, w); mt.Translate(450, -100); s2::StatTopNodes::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); // mt.Translate(450, 180); // s2::StatSymbol::Instance()->Print(buf_str); // GTxt::Instance()->Draw(mt, buf_str, w); // buf_str.clear(); // mt.Translate(0, -230); // sl::StatDrawCall::Instance()->Print(buf_str); // GTxt::Instance()->Draw(mt, buf_str, w); // buf_str.clear(); mgr->FlushShader(); } void Statistics::PrintConsole() const { static const int PRINT_COUNT = 30; static int count = 0; ++count; if (count == PRINT_COUNT) { count = 0; sl::Statistics* stat = sl::Statistics::Instance(); int dc = stat->GetDrawCall(); int count = stat->GetVertices(); float fps_curr = StatFPS::Instance()->GetFPSCurr(); float curr_cost = 0; if (fps_curr != 0) { curr_cost = 1000.0f / fps_curr; } LOGI("fps %.1f, cost %.1f, dc %d, vertices %d, cost avg %.1f\n", 1000.0f / m_tpf_smooth, m_tpf_smooth, dc, count, curr_cost); } } void Statistics::PrintFile() const { sl::Statistics* sl_stat = sl::Statistics::Instance(); static char buf[512]; sprintf(buf, "timestamp %lu, cost %.1f, vertices %d, dc %d\n", time(NULL), m_tpf_smooth, sl_stat->GetVertices(), sl_stat->GetDrawCall()); m_fout << buf; // static std::string buf_str; // buf_str.reserve(1024); // s2::StatTopNodes::Instance()->Print(buf_str); // m_fout << buf_str; static const int FLUSH_COUNT = 100; static int count = 0; ++count; if (count == FLUSH_COUNT) { count = 0; m_fout.flush(); } } }<|endoftext|>
<commit_before>/* * Trajectory class representing a trajectory in state space * * Author: Andrew Barry, <abarry@csail.mit.edu> 2013-2015 * */ #include "Trajectory.hpp" // Constructor that loads a trajectory from a file Trajectory::Trajectory() { trajectory_number_ = -1; dimension_ = 0; udimension_ = 0; filename_prefix_ = ""; dt_ = 0; } Trajectory::Trajectory(std::string filename_prefix, bool quiet) : Trajectory() { LoadTrajectory(filename_prefix, quiet); } void Trajectory::LoadTrajectory(std::string filename_prefix, bool quiet) { // open the file std::vector<std::vector<std::string>> strs; if (!quiet) { std::cout << "Loading trajectory: " << std::endl << "\t" << filename_prefix << std::endl; } std::string traj_number_str = filename_prefix.substr(filename_prefix.length() - 5, 5); trajectory_number_ = std::stoi(traj_number_str); LoadMatrixFromCSV(filename_prefix + "-x.csv", xpoints_, quiet); LoadMatrixFromCSV(filename_prefix + "-u.csv", upoints_, quiet); LoadMatrixFromCSV(filename_prefix + "-controller.csv", kpoints_, quiet); LoadMatrixFromCSV(filename_prefix + "-affine.csv", affine_points_, quiet); filename_prefix_ = filename_prefix; dimension_ = xpoints_.cols() - 1; // minus 1 because of time index udimension_ = upoints_.cols() - 1; if (kpoints_.cols() - 1 != dimension_ * udimension_) { std::cerr << "Error: expected to have " << dimension_ << "*" << udimension_ << "+1 = " << dimension_ * udimension_ + 1 << " columns in " << filename_prefix << "-controller.csv but found " << kpoints_.cols() << std::endl; exit(1); } if (affine_points_.cols() - 1 != udimension_) { std::cerr << "Error: expected to have " << udimension_ << "+1 = " << udimension_ + 1 << " columns in " << filename_prefix << "-affine.csv but found " << affine_points_.cols() << std::endl; exit(1); } if (upoints_.rows() != kpoints_.rows() || upoints_.rows() != affine_points_.rows()) { std::cerr << "Error: inconsistent number of rows in CSV files: " << std::endl << "\t" << filename_prefix << "-x: " << xpoints_.rows() << std::endl << "\t" << filename_prefix << "-u: " << upoints_.rows() << std::endl << "\t" << filename_prefix << "-controller: " << kpoints_.rows() << std::endl << "\t" << filename_prefix << "-affine: " << affine_points_.rows() << std::endl; exit(1); } // set the minimum altitude BotTrans trans; bot_trans_set_identity(&trans); bool first_run = true; for (int i = 0; i < GetNumberOfPoints(); i++) { double this_t = GetTimeAtIndex(i); double xyz[3]; GetXyzYawTransformedPoint(this_t, trans, xyz); if (xyz[2] < min_altitude_ || first_run == true) { min_altitude_ = xyz[2]; first_run = false; } } } void Trajectory::LoadMatrixFromCSV( const std::string& filename, Eigen::MatrixXd &matrix, bool quiet) { if (!quiet) { std::cout << "Loading " << filename << std::endl; } int number_of_lines = GetNumberOfLines(filename); int row_num = 0; int i = 0; // file, delimiter, first_line_is_header? CsvParser *csvparser = CsvParser_new(filename.c_str(), ",", true); CsvRow *header; CsvRow *row; header = CsvParser_getHeader(csvparser); if (header == NULL) { printf("%s\n", CsvParser_getErrorMessage(csvparser)); return; } // note: do not remove the getFields(header) call as it has // side effects we need even if we don't use the headers //char **headerFields = CsvParser_getFields(header); CsvParser_getFields(header); for (i = 0 ; i < CsvParser_getNumFields(header) ; i++) { //printf("TITLE: %s\n", headerFields[i]); } matrix.resize(number_of_lines - 1, i); // minus 1 for header, i = number of columns while ((row = CsvParser_getRow(csvparser)) ) { //printf("NEW LINE:\n"); char **rowFields = CsvParser_getFields(row); for (i = 0 ; i < CsvParser_getNumFields(row) ; i++) { matrix(row_num, i) = atof(rowFields[i]); //printf("FIELD: %20.20f\n", atof(rowFields[i])); } CsvParser_destroy_row(row); if (row_num == 1) { dt_ = matrix(1, 0) - matrix(0, 0); } else if (row_num > 1) { if (matrix(row_num, 0) - matrix(row_num - 1, 0) - dt_ > 5*std::numeric_limits<double>::epsilon()) { std::cerr << "Error: non-constant dt. Expected dt = " << dt_ << " but got matrix[" << row_num << "][0] - matrix[" << row_num - 1 << "][0] = " << matrix(row_num, 0) - matrix(row_num - 1, 0) << " (residual = " << (matrix(row_num, 0) - matrix(row_num - 1, 0) - dt_) << std::endl; std::cout << matrix << std::endl; exit(1); } } row_num ++; } CsvParser_destroy(csvparser); } int Trajectory::GetNumberOfLines(std::string filename) const { int number_of_lines = 0; std::string line; std::ifstream myfile(filename); while (getline(myfile, line)) { ++number_of_lines; } return number_of_lines; } Eigen::VectorXd Trajectory::GetState(double t) const { int index = GetIndexAtTime(t); Eigen::VectorXd row_vec = xpoints_.row(index); return row_vec.tail(xpoints_.cols() - 1); // remove time } Eigen::VectorXd Trajectory::GetUCommand(double t) const { int index = GetIndexAtTime(t); Eigen::VectorXd row_vec = upoints_.row(index); return row_vec.tail(upoints_.cols() - 1); // remove time } /** * Assuming a constant dt, we can compute the index of a point * based on its time. * * @param t time to find index of * @param (optional) use_rollout set to true to use time bounds from rollout instead of xpoints * @retval index of nearest point */ int Trajectory::GetIndexAtTime(double t) const { // round t to the nearest dt_ double t0, tf; t0 = xpoints_(0,0); tf = xpoints_(xpoints_.rows() - 1, 0); if (t <= t0) { return 0; } else if (t >= tf) { return xpoints_.rows() - 1; } //std::cout << "after" << std::endl; // otherwise, we are somewhere in the bounds of the trajectory int num_dts = std::round(t/dt_); float remainder = std::remainder(t, dt_); //std::cout << "t = " << t << " remainder = " << remainder << " num_dts = " << num_dts << std::endl; if (remainder > 0.5f*dt_) { num_dts++; } int starting_dts = t0 / dt_; return num_dts + starting_dts; } TEST(Trajectory, GetIndexAtTimeTest) { Trajectory traj("trajtest/ti/TI-test-TI-straight-pd-no-yaw-00000", true); EXPECT_EQ_ARM(traj.GetIndexAtTime(0), 0); EXPECT_EQ_ARM(traj.GetMaxTime(), 3); EXPECT_EQ_ARM(traj.GetNumberOfPoints(), 301); EXPECT_EQ_ARM(traj.GetIndexAtTime(1000), 300); EXPECT_EQ_ARM(traj.GetIndexAtTime(0.0001), 0); EXPECT_EQ_ARM(traj.GetIndexAtTime(0.01), 1); EXPECT_EQ_ARM(traj.GetIndexAtTime(0.02), 2); EXPECT_EQ_ARM(traj.GetIndexAtTime(0.019), 2); EXPECT_EQ_ARM(traj.GetIndexAtTime(0.021), 2); EXPECT_EQ_ARM(traj.GetIndexAtTime(0.90), 90); } /** * Unpacks the gain matrix for a specific time t. * * This could be pre-computed if it becomes a performance bottleneck. * * @param t time along the trajectory * * @retval gain matrix at that time with dimension: state_dimension x u_dimension */ Eigen::MatrixXd Trajectory::GetGainMatrix(double t) const { int index = GetIndexAtTime(t); Eigen::VectorXd k_row = kpoints_.row(index); Eigen::MatrixXd k_mat(udimension_, dimension_); for (int i = 0; i < udimension_; i++) { // +1 because the column index is time int start_pos = i * dimension_ + 1; k_mat.row(i) = k_row.segment(start_pos, dimension_); } return k_mat; } void Trajectory::Print() const { std::cout << "------------ Trajectory print -------------" << std::endl; std::cout << "Filename: " << filename_prefix_ << std::endl; std::cout << "Trajectory number: " << trajectory_number_ << std::endl; std::cout << "Dimension: " << dimension_ << std::endl; std::cout << "u-dimension: " << udimension_ << std::endl; std::cout << " t\t x\t y\t z\t roll\t pitch\t yaw \t xdot\t ydot\t zdot\t rolld\t pitchd\t yawd" << std::endl; std::cout << xpoints_ << std::endl; std::cout << "------------- u points ----------------" << std::endl; std::cout << " t\t u1\t u2\t u3" << std::endl; std::cout << upoints_ << std::endl; std::cout << "------------- k points ----------------" << std::endl; std::cout << kpoints_ << std::endl; std::cout << "------------- affine points ----------------" << std::endl; std::cout << affine_points_ << std::endl; } /** * Returns a point along the trajectory transformed with xyz and yaw. Ignores pitch and roll. */ void Trajectory::GetXyzYawTransformedPoint(double t, const BotTrans &transform, double *xyz) const { // apply the transformation from the global frame: orgin = (0,0,0) // to the local frame point Eigen::VectorXd state = GetState(t); double original_point[3]; original_point[0] = state(0); original_point[1] = state(1); original_point[2] = state(2); // remove roll and pitch from the transform BotTrans trans_xyz_yaw; bot_trans_copy(&trans_xyz_yaw, &transform); double rpy[3]; bot_quat_to_roll_pitch_yaw(trans_xyz_yaw.rot_quat, rpy); rpy[0] = 0; rpy[1] = 0; bot_roll_pitch_yaw_to_quat(rpy, trans_xyz_yaw.rot_quat); bot_trans_apply_vec(&trans_xyz_yaw, original_point, xyz); } void Trajectory::Draw(bot_lcmgl_t *lcmgl, const BotTrans *transform) const { if (transform == nullptr) { BotTrans temp_trans; bot_trans_set_identity(&temp_trans); transform = &temp_trans; } // draw the trajectory's origin double xyz[3]; float origin_size[3] = { .25, .25, .25 }; GetXyzYawTransformedPoint(0, *transform, xyz); bot_lcmgl_box(lcmgl, xyz, origin_size); bot_lcmgl_line_width(lcmgl, 2.0f); bot_lcmgl_begin(lcmgl, GL_LINE_STRIP); double t = 0; while (t < GetMaxTime()) { GetXyzYawTransformedPoint(t, *transform, xyz); bot_lcmgl_vertex3f(lcmgl, xyz[0], xyz[1], xyz[2]); t += GetDT(); } bot_lcmgl_end(lcmgl); t = 0; while (t < GetMaxTime()) { GetXyzYawTransformedPoint(t, *transform, xyz); bot_lcmgl_sphere(lcmgl, xyz, 0.05, 20, 20); t += GetDT(); } // label the last point with a timestamp //char t_end[50]; //sprintf(t_end, "t = %.2fs", GetMaxTime()); //bot_lcmgl_text_ex(lcmgl, xyz, t_end, 0, //BOT_GL_DRAW_TEXT_JUSTIFY_CENTER | //BOT_GL_DRAW_TEXT_ANCHOR_HCENTER | //BOT_GL_DRAW_TEXT_ANCHOR_VCENTER); } /** * Searches along the remainder of the trajectory, assuming it executes exactly from the * current position. * * Returns the distance to the closest obstacle over that search. Used for determining if * replanning is required * * @param octomap Obstacle map * @param bodyToLocal Current position of the aircraft * @param current_t Time along the trajectory * * @retval Distance to the closest obstacle along the remainder of the trajectory */ double Trajectory::ClosestObstacleInRemainderOfTrajectory(const StereoOctomap &octomap, const BotTrans &body_to_local, double current_t) const { // for each point remaining in the trajectory int number_of_points = GetNumberOfPoints(); int starting_index = GetIndexAtTime(current_t); std::vector<double> point_distances(number_of_points); // TODO: potentially inefficient double closest_obstacle_distance = -1; for (int i = starting_index; i < number_of_points; i++) { // for each point in the trajectory // subtract the current position (ie move the trajectory to where we are) double transformed_point[3]; double this_t = GetTimeAtIndex(i); GetXyzYawTransformedPoint(this_t, body_to_local, transformed_point); // check if there is an obstacle nearby point_distances.at(i) = octomap.NearestNeighbor(transformed_point); } for (int i = starting_index; i < number_of_points; i++) { double distance_to_point = point_distances.at(i); if (distance_to_point >= 0) { if (distance_to_point < closest_obstacle_distance || closest_obstacle_distance < 0) { closest_obstacle_distance = distance_to_point; } } } // check minumum altitude double min_altitude = GetMinimumAltitude() + body_to_local.trans_vec[2]; if (min_altitude < 0) { // this trajectory would impact the ground closest_obstacle_distance = 0; } else if (min_altitude < closest_obstacle_distance || closest_obstacle_distance < 0) { closest_obstacle_distance = min_altitude; } return closest_obstacle_distance; } <commit_msg>altitude fix<commit_after>/* * Trajectory class representing a trajectory in state space * * Author: Andrew Barry, <abarry@csail.mit.edu> 2013-2015 * */ #include "Trajectory.hpp" // Constructor that loads a trajectory from a file Trajectory::Trajectory() { trajectory_number_ = -1; dimension_ = 0; udimension_ = 0; filename_prefix_ = ""; dt_ = 0; } Trajectory::Trajectory(std::string filename_prefix, bool quiet) : Trajectory() { LoadTrajectory(filename_prefix, quiet); } void Trajectory::LoadTrajectory(std::string filename_prefix, bool quiet) { // open the file std::vector<std::vector<std::string>> strs; if (!quiet) { std::cout << "Loading trajectory: " << std::endl << "\t" << filename_prefix << std::endl; } std::string traj_number_str = filename_prefix.substr(filename_prefix.length() - 5, 5); trajectory_number_ = std::stoi(traj_number_str); LoadMatrixFromCSV(filename_prefix + "-x.csv", xpoints_, quiet); LoadMatrixFromCSV(filename_prefix + "-u.csv", upoints_, quiet); LoadMatrixFromCSV(filename_prefix + "-controller.csv", kpoints_, quiet); LoadMatrixFromCSV(filename_prefix + "-affine.csv", affine_points_, quiet); filename_prefix_ = filename_prefix; dimension_ = xpoints_.cols() - 1; // minus 1 because of time index udimension_ = upoints_.cols() - 1; if (kpoints_.cols() - 1 != dimension_ * udimension_) { std::cerr << "Error: expected to have " << dimension_ << "*" << udimension_ << "+1 = " << dimension_ * udimension_ + 1 << " columns in " << filename_prefix << "-controller.csv but found " << kpoints_.cols() << std::endl; exit(1); } if (affine_points_.cols() - 1 != udimension_) { std::cerr << "Error: expected to have " << udimension_ << "+1 = " << udimension_ + 1 << " columns in " << filename_prefix << "-affine.csv but found " << affine_points_.cols() << std::endl; exit(1); } if (upoints_.rows() != kpoints_.rows() || upoints_.rows() != affine_points_.rows()) { std::cerr << "Error: inconsistent number of rows in CSV files: " << std::endl << "\t" << filename_prefix << "-x: " << xpoints_.rows() << std::endl << "\t" << filename_prefix << "-u: " << upoints_.rows() << std::endl << "\t" << filename_prefix << "-controller: " << kpoints_.rows() << std::endl << "\t" << filename_prefix << "-affine: " << affine_points_.rows() << std::endl; exit(1); } // set the minimum altitude BotTrans trans; bot_trans_set_identity(&trans); bool first_run = true; for (int i = 0; i < GetNumberOfPoints(); i++) { double this_t = GetTimeAtIndex(i); double xyz[3]; GetXyzYawTransformedPoint(this_t, trans, xyz); if (xyz[2] < min_altitude_ || first_run == true) { min_altitude_ = xyz[2]; first_run = false; } } } void Trajectory::LoadMatrixFromCSV( const std::string& filename, Eigen::MatrixXd &matrix, bool quiet) { if (!quiet) { std::cout << "Loading " << filename << std::endl; } int number_of_lines = GetNumberOfLines(filename); int row_num = 0; int i = 0; // file, delimiter, first_line_is_header? CsvParser *csvparser = CsvParser_new(filename.c_str(), ",", true); CsvRow *header; CsvRow *row; header = CsvParser_getHeader(csvparser); if (header == NULL) { printf("%s\n", CsvParser_getErrorMessage(csvparser)); return; } // note: do not remove the getFields(header) call as it has // side effects we need even if we don't use the headers //char **headerFields = CsvParser_getFields(header); CsvParser_getFields(header); for (i = 0 ; i < CsvParser_getNumFields(header) ; i++) { //printf("TITLE: %s\n", headerFields[i]); } matrix.resize(number_of_lines - 1, i); // minus 1 for header, i = number of columns while ((row = CsvParser_getRow(csvparser)) ) { //printf("NEW LINE:\n"); char **rowFields = CsvParser_getFields(row); for (i = 0 ; i < CsvParser_getNumFields(row) ; i++) { matrix(row_num, i) = atof(rowFields[i]); //printf("FIELD: %20.20f\n", atof(rowFields[i])); } CsvParser_destroy_row(row); if (row_num == 1) { dt_ = matrix(1, 0) - matrix(0, 0); } else if (row_num > 1) { if (matrix(row_num, 0) - matrix(row_num - 1, 0) - dt_ > 5*std::numeric_limits<double>::epsilon()) { std::cerr << "Error: non-constant dt. Expected dt = " << dt_ << " but got matrix[" << row_num << "][0] - matrix[" << row_num - 1 << "][0] = " << matrix(row_num, 0) - matrix(row_num - 1, 0) << " (residual = " << (matrix(row_num, 0) - matrix(row_num - 1, 0) - dt_) << std::endl; std::cout << matrix << std::endl; exit(1); } } row_num ++; } CsvParser_destroy(csvparser); } int Trajectory::GetNumberOfLines(std::string filename) const { int number_of_lines = 0; std::string line; std::ifstream myfile(filename); while (getline(myfile, line)) { ++number_of_lines; } return number_of_lines; } Eigen::VectorXd Trajectory::GetState(double t) const { int index = GetIndexAtTime(t); Eigen::VectorXd row_vec = xpoints_.row(index); return row_vec.tail(xpoints_.cols() - 1); // remove time } Eigen::VectorXd Trajectory::GetUCommand(double t) const { int index = GetIndexAtTime(t); Eigen::VectorXd row_vec = upoints_.row(index); return row_vec.tail(upoints_.cols() - 1); // remove time } /** * Assuming a constant dt, we can compute the index of a point * based on its time. * * @param t time to find index of * @param (optional) use_rollout set to true to use time bounds from rollout instead of xpoints * @retval index of nearest point */ int Trajectory::GetIndexAtTime(double t) const { // round t to the nearest dt_ double t0, tf; t0 = xpoints_(0,0); tf = xpoints_(xpoints_.rows() - 1, 0); if (t <= t0) { return 0; } else if (t >= tf) { return xpoints_.rows() - 1; } //std::cout << "after" << std::endl; // otherwise, we are somewhere in the bounds of the trajectory int num_dts = std::round(t/dt_); float remainder = std::remainder(t, dt_); //std::cout << "t = " << t << " remainder = " << remainder << " num_dts = " << num_dts << std::endl; if (remainder > 0.5f*dt_) { num_dts++; } int starting_dts = t0 / dt_; return num_dts + starting_dts; } TEST(Trajectory, GetIndexAtTimeTest) { Trajectory traj("trajtest/ti/TI-test-TI-straight-pd-no-yaw-00000", true); EXPECT_EQ_ARM(traj.GetIndexAtTime(0), 0); EXPECT_EQ_ARM(traj.GetMaxTime(), 3); EXPECT_EQ_ARM(traj.GetNumberOfPoints(), 301); EXPECT_EQ_ARM(traj.GetIndexAtTime(1000), 300); EXPECT_EQ_ARM(traj.GetIndexAtTime(0.0001), 0); EXPECT_EQ_ARM(traj.GetIndexAtTime(0.01), 1); EXPECT_EQ_ARM(traj.GetIndexAtTime(0.02), 2); EXPECT_EQ_ARM(traj.GetIndexAtTime(0.019), 2); EXPECT_EQ_ARM(traj.GetIndexAtTime(0.021), 2); EXPECT_EQ_ARM(traj.GetIndexAtTime(0.90), 90); } /** * Unpacks the gain matrix for a specific time t. * * This could be pre-computed if it becomes a performance bottleneck. * * @param t time along the trajectory * * @retval gain matrix at that time with dimension: state_dimension x u_dimension */ Eigen::MatrixXd Trajectory::GetGainMatrix(double t) const { int index = GetIndexAtTime(t); Eigen::VectorXd k_row = kpoints_.row(index); Eigen::MatrixXd k_mat(udimension_, dimension_); for (int i = 0; i < udimension_; i++) { // +1 because the column index is time int start_pos = i * dimension_ + 1; k_mat.row(i) = k_row.segment(start_pos, dimension_); } return k_mat; } void Trajectory::Print() const { std::cout << "------------ Trajectory print -------------" << std::endl; std::cout << "Filename: " << filename_prefix_ << std::endl; std::cout << "Trajectory number: " << trajectory_number_ << std::endl; std::cout << "Dimension: " << dimension_ << std::endl; std::cout << "u-dimension: " << udimension_ << std::endl; std::cout << " t\t x\t y\t z\t roll\t pitch\t yaw \t xdot\t ydot\t zdot\t rolld\t pitchd\t yawd" << std::endl; std::cout << xpoints_ << std::endl; std::cout << "------------- u points ----------------" << std::endl; std::cout << " t\t u1\t u2\t u3" << std::endl; std::cout << upoints_ << std::endl; std::cout << "------------- k points ----------------" << std::endl; std::cout << kpoints_ << std::endl; std::cout << "------------- affine points ----------------" << std::endl; std::cout << affine_points_ << std::endl; } /** * Returns a point along the trajectory transformed with xyz and yaw. Ignores pitch and roll. */ void Trajectory::GetXyzYawTransformedPoint(double t, const BotTrans &transform, double *xyz) const { // apply the transformation from the global frame: orgin = (0,0,0) // to the local frame point Eigen::VectorXd state = GetState(t); double original_point[3]; original_point[0] = state(0); original_point[1] = state(1); original_point[2] = state(2); // remove roll and pitch from the transform BotTrans trans_xyz_yaw; bot_trans_copy(&trans_xyz_yaw, &transform); double rpy[3]; bot_quat_to_roll_pitch_yaw(trans_xyz_yaw.rot_quat, rpy); rpy[0] = 0; rpy[1] = 0; bot_roll_pitch_yaw_to_quat(rpy, trans_xyz_yaw.rot_quat); bot_trans_apply_vec(&trans_xyz_yaw, original_point, xyz); } void Trajectory::Draw(bot_lcmgl_t *lcmgl, const BotTrans *transform) const { if (transform == nullptr) { BotTrans temp_trans; bot_trans_set_identity(&temp_trans); transform = &temp_trans; } // draw the trajectory's origin double xyz[3]; float origin_size[3] = { .25, .25, .25 }; GetXyzYawTransformedPoint(0, *transform, xyz); bot_lcmgl_box(lcmgl, xyz, origin_size); bot_lcmgl_line_width(lcmgl, 2.0f); bot_lcmgl_begin(lcmgl, GL_LINE_STRIP); double t = 0; while (t < GetMaxTime()) { GetXyzYawTransformedPoint(t, *transform, xyz); bot_lcmgl_vertex3f(lcmgl, xyz[0], xyz[1], xyz[2]); t += GetDT(); } bot_lcmgl_end(lcmgl); t = 0; while (t < GetMaxTime()) { GetXyzYawTransformedPoint(t, *transform, xyz); bot_lcmgl_sphere(lcmgl, xyz, 0.05, 20, 20); t += GetDT(); } // label the last point with a timestamp //char t_end[50]; //sprintf(t_end, "t = %.2fs", GetMaxTime()); //bot_lcmgl_text_ex(lcmgl, xyz, t_end, 0, //BOT_GL_DRAW_TEXT_JUSTIFY_CENTER | //BOT_GL_DRAW_TEXT_ANCHOR_HCENTER | //BOT_GL_DRAW_TEXT_ANCHOR_VCENTER); } /** * Searches along the remainder of the trajectory, assuming it executes exactly from the * current position. * * Returns the distance to the closest obstacle over that search. Used for determining if * replanning is required * * @param octomap Obstacle map * @param bodyToLocal Current position of the aircraft * @param current_t Time along the trajectory * * @retval Distance to the closest obstacle along the remainder of the trajectory */ double Trajectory::ClosestObstacleInRemainderOfTrajectory(const StereoOctomap &octomap, const BotTrans &body_to_local, double current_t) const { // for each point remaining in the trajectory int number_of_points = GetNumberOfPoints(); int starting_index = GetIndexAtTime(current_t); std::vector<double> point_distances(number_of_points); // TODO: potentially inefficient double closest_obstacle_distance = -1; for (int i = starting_index; i < number_of_points; i++) { // for each point in the trajectory // subtract the current position (ie move the trajectory to where we are) double transformed_point[3]; double this_t = GetTimeAtIndex(i); GetXyzYawTransformedPoint(this_t, body_to_local, transformed_point); // check if there is an obstacle nearby point_distances.at(i) = octomap.NearestNeighbor(transformed_point); } for (int i = starting_index; i < number_of_points; i++) { double distance_to_point = point_distances.at(i); if (distance_to_point >= 0) { if (distance_to_point < closest_obstacle_distance || closest_obstacle_distance < 0) { closest_obstacle_distance = distance_to_point; } } } // check minumum altitude double min_altitude = GetMinimumAltitude() + body_to_local.trans_vec[2]; if (min_altitude < 0) { //// TODO FIXME HACK SHOULD BE A PARAM // this trajectory would impact the ground closest_obstacle_distance = 0; }// else if (min_altitude < closest_obstacle_distance || closest_obstacle_distance < 0) { // closest_obstacle_distance = min_altitude; //} return closest_obstacle_distance; } <|endoftext|>
<commit_before>#include "movable_entity.h" #include <iostream> // TODO remove! #include <algorithm> using namespace space_invaders; MovableEntity::MovableEntity(Game& game) : DrawableEntity(game), mStepSize(0), mStepCounter(0), mVelocity(0.f), mDirectionX(0.f), mDirectionY(0.f) { // ... } void MovableEntity::update(unsigned long dt) { DrawableEntity::update(dt); mStepCounter = std::max(0, mStepCounter - 1); if (mStepCounter <= 0) { this->setX(this->getX() + mDirectionX * mVelocity * dt); this->setY(this->getY() + mDirectionY * mVelocity * dt); mStepCounter = mStepSize; } } void MovableEntity::setStepSize(int stepSize) { mStepSize = stepSize; mStepCounter = stepSize; }<commit_msg>Removed the unnecessary #include <iostream> from the movable_entity.cpp<commit_after>#include "movable_entity.h" #include <algorithm> using namespace space_invaders; MovableEntity::MovableEntity(Game& game) : DrawableEntity(game), mStepSize(0), mStepCounter(0), mVelocity(0.f), mDirectionX(0.f), mDirectionY(0.f) { // ... } void MovableEntity::update(unsigned long dt) { DrawableEntity::update(dt); mStepCounter = std::max(0, mStepCounter - 1); if (mStepCounter <= 0) { this->setX(this->getX() + mDirectionX * mVelocity * dt); this->setY(this->getY() + mDirectionY * mVelocity * dt); mStepCounter = mStepSize; } } void MovableEntity::setStepSize(int stepSize) { mStepSize = stepSize; mStepCounter = stepSize; }<|endoftext|>
<commit_before>#include "utils/rename-existing/rename-existing-2.h" #include <QDir> #include <QFile> #include <ui_rename-existing-2.h> #include "functions.h" #include "logger.h" #include "rename-existing-table-model.h" RenameExisting2::RenameExisting2(QList<RenameExistingFile> details, QString folder, QWidget *parent) : QDialog(parent), ui(new Ui::RenameExisting2), m_details(std::move(details)), m_folder(std::move(folder)) { ui->setupUi(this); m_model = new RenameExistingTableModel(m_details, m_folder, this); ui->tableView->setModel(m_model); QHeaderView *verticalHeader = ui->tableView->verticalHeader(); verticalHeader->setSectionResizeMode(QHeaderView::Fixed); verticalHeader->setDefaultSectionSize(50); QHeaderView *headerView = ui->tableView->horizontalHeader(); headerView->setSectionResizeMode(QHeaderView::Interactive); headerView->resizeSection(0, 50); headerView->setSectionResizeMode(1, QHeaderView::Stretch); headerView->setSectionResizeMode(2, QHeaderView::Stretch); } RenameExisting2::~RenameExisting2() { delete ui; } void RenameExisting2::on_buttonCancel_clicked() { emit rejected(); close(); } void RenameExisting2::deleteDir(const QString &path) { if (path == m_folder) { return; } QDir directory(path); if (directory.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).count() == 0) { directory.removeRecursively(); const QString parent = path.left(path.lastIndexOf(QDir::separator())); deleteDir(parent); } } void RenameExisting2::on_buttonOk_clicked() { // Move all images for (const RenameExistingFile &image : qAsConst(m_details)) { // Ignore images with no change in path if (image.newPath.isEmpty() || image.newPath == image.path) { continue; } // Create hierarchy const QString path = image.newPath.left(image.newPath.lastIndexOf(QDir::separator())); QDir directory(path); if (!directory.exists()) { QDir dir; if (!dir.mkpath(path)) { log(QStringLiteral("Could not create destination directory"), Logger::Error); } } // Move file QFile::rename(image.path, image.newPath); for (const QString &child : image.children) { const QString newPath = QString(child).replace(image.path, image.newPath); QFile::rename(child, newPath); } // Delete old path if necessary const QString oldDir = image.path.left(image.path.lastIndexOf(QDir::separator())); deleteDir(oldDir); } // Close emit accepted(); close(); } <commit_msg>Add warnings when image renamer failed to rename a file<commit_after>#include "utils/rename-existing/rename-existing-2.h" #include <QDir> #include <QFile> #include <ui_rename-existing-2.h> #include "functions.h" #include "logger.h" #include "rename-existing-table-model.h" RenameExisting2::RenameExisting2(QList<RenameExistingFile> details, QString folder, QWidget *parent) : QDialog(parent), ui(new Ui::RenameExisting2), m_details(std::move(details)), m_folder(std::move(folder)) { ui->setupUi(this); m_model = new RenameExistingTableModel(m_details, m_folder, this); ui->tableView->setModel(m_model); QHeaderView *verticalHeader = ui->tableView->verticalHeader(); verticalHeader->setSectionResizeMode(QHeaderView::Fixed); verticalHeader->setDefaultSectionSize(50); QHeaderView *headerView = ui->tableView->horizontalHeader(); headerView->setSectionResizeMode(QHeaderView::Interactive); headerView->resizeSection(0, 50); headerView->setSectionResizeMode(1, QHeaderView::Stretch); headerView->setSectionResizeMode(2, QHeaderView::Stretch); } RenameExisting2::~RenameExisting2() { delete ui; } void RenameExisting2::on_buttonCancel_clicked() { emit rejected(); close(); } void RenameExisting2::deleteDir(const QString &path) { if (path == m_folder) { return; } QDir directory(path); if (directory.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries).count() == 0) { directory.removeRecursively(); const QString parent = path.left(path.lastIndexOf(QDir::separator())); deleteDir(parent); } } void RenameExisting2::on_buttonOk_clicked() { // Move all images for (const RenameExistingFile &image : qAsConst(m_details)) { // Ignore images with no change in path if (image.newPath.isEmpty() || image.newPath == image.path) { continue; } // Create hierarchy const QString path = image.newPath.left(image.newPath.lastIndexOf(QDir::separator())); QDir directory(path); if (!directory.exists()) { QDir dir; if (!dir.mkpath(path)) { log(QStringLiteral("Could not create destination directory"), Logger::Error); } } // Move file if (!QFile::rename(image.path, image.newPath)) { log(QStringLiteral("Could not rename file from `%1` to `%2`").arg(image.path, image.newPath), Logger::Error); } for (const QString &child : image.children) { const QString newPath = QString(child).replace(image.path, image.newPath); if (!QFile::rename(child, newPath)) { log(QStringLiteral("Could not rename child file from `%1` to `%2`").arg(image.path, image.newPath), Logger::Error); } } // Delete old path if necessary const QString oldDir = image.path.left(image.path.lastIndexOf(QDir::separator())); deleteDir(oldDir); } // Close emit accepted(); close(); } <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2014 * Solidity commandline compiler. */ #include <string> #include <iostream> #include <boost/program_options.hpp> #include "BuildInfo.h" #include <libdevcore/Common.h> #include <libdevcore/CommonData.h> #include <libdevcore/CommonIO.h> #include <libevmcore/Instruction.h> #include <libsolidity/Scanner.h> #include <libsolidity/Parser.h> #include <libsolidity/ASTPrinter.h> #include <libsolidity/NameAndTypeResolver.h> #include <libsolidity/Exceptions.h> #include <libsolidity/CompilerStack.h> #include <libsolidity/SourceReferenceFormatter.h> using namespace std; using namespace dev; using namespace solidity; namespace po = boost::program_options; void version() { cout << "solc, the solidity complier commandline interface " << dev::Version << endl << " by Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com>, (c) 2014." << endl << "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl; exit(0); } int main(int argc, char** argv) { // Declare the supported options. po::options_description desc("Allowed options"); desc.add_options() ("help", "Show help message and exit") ("version", "Show version and exit") ("optimize", po::value<bool>()->default_value(false), "Optimize bytecode for size") ("input-file", po::value<vector<string>>(), "input file"); // All positional options should be interpreted as input files po::positional_options_description p; p.add("input-file", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("help")) { cout << desc; return 0; } if (vm.count("version")) { version(); return 0; } map<string, string> sourceCodes; if (!vm.count("input-file")) { string s; while (!cin.eof()) { getline(cin, s); sourceCodes["<stdin>"].append(s); } } else for (string const& infile: vm["input-file"].as<vector<string>>()) sourceCodes[infile] = asString(dev::contents(infile)); CompilerStack compiler; try { for (auto const& sourceCode: sourceCodes) compiler.addSource(sourceCode.first, sourceCode.second); compiler.compile( vm["optimize"].as<bool>()); } catch (ParserError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", compiler); return -1; } catch (DeclarationError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", compiler); return -1; } catch (TypeError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", compiler); return -1; } catch (CompilerError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", compiler); return -1; } catch (InternalCompilerError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Internal compiler error", compiler); return -1; } catch (Exception const& exception) { cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl; return -1; } catch (...) { cerr << "Unknown exception during compilation." << endl; return -1; } cout << "Syntax trees:" << endl << endl; for (auto const& sourceCode: sourceCodes) { cout << endl << "======= " << sourceCode.first << " =======" << endl; ASTPrinter printer(compiler.getAST(sourceCode.first), sourceCode.second); printer.print(cout); } vector<string> contracts = compiler.getContractNames(); cout << endl << "Contracts:" << endl; for (string const& contract: contracts) { cout << endl << "======= " << contract << " =======" << endl << "EVM assembly:" << endl; compiler.streamAssembly(cout, contract); cout << "Opcodes:" << endl << eth::disassemble(compiler.getBytecode(contract)) << endl << "Binary: " << toHex(compiler.getBytecode(contract)) << endl << "Interface specification: " << compiler.getJsonDocumentation(contract, DocumentationType::ABI_INTERFACE) << endl << "Natspec user documentation: " << compiler.getJsonDocumentation(contract, DocumentationType::NATSPEC_USER) << endl << "Natspec developer documentation: " << compiler.getJsonDocumentation(contract, DocumentationType::NATSPEC_DEV) << endl; } return 0; } <commit_msg>Unknown solc arguments are now ignored<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2014 * Solidity commandline compiler. */ #include <string> #include <iostream> #include <boost/program_options.hpp> #include "BuildInfo.h" #include <libdevcore/Common.h> #include <libdevcore/CommonData.h> #include <libdevcore/CommonIO.h> #include <libevmcore/Instruction.h> #include <libsolidity/Scanner.h> #include <libsolidity/Parser.h> #include <libsolidity/ASTPrinter.h> #include <libsolidity/NameAndTypeResolver.h> #include <libsolidity/Exceptions.h> #include <libsolidity/CompilerStack.h> #include <libsolidity/SourceReferenceFormatter.h> using namespace std; using namespace dev; using namespace solidity; namespace po = boost::program_options; void version() { cout << "solc, the solidity complier commandline interface " << dev::Version << endl << " by Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com>, (c) 2014." << endl << "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl; exit(0); } int main(int argc, char** argv) { // Declare the supported options. po::options_description desc("Allowed options"); desc.add_options() ("help", "Show help message and exit") ("version", "Show version and exit") ("optimize", po::value<bool>()->default_value(false), "Optimize bytecode for size") ("input-file", po::value<vector<string>>(), "input file"); // All positional options should be interpreted as input files po::positional_options_description p; p.add("input-file", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), vm); po::notify(vm); if (vm.count("help")) { cout << desc; return 0; } if (vm.count("version")) { version(); return 0; } map<string, string> sourceCodes; if (!vm.count("input-file")) { string s; while (!cin.eof()) { getline(cin, s); sourceCodes["<stdin>"].append(s); } } else for (string const& infile: vm["input-file"].as<vector<string>>()) sourceCodes[infile] = asString(dev::contents(infile)); CompilerStack compiler; try { for (auto const& sourceCode: sourceCodes) compiler.addSource(sourceCode.first, sourceCode.second); compiler.compile( vm["optimize"].as<bool>()); } catch (ParserError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", compiler); return -1; } catch (DeclarationError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", compiler); return -1; } catch (TypeError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", compiler); return -1; } catch (CompilerError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", compiler); return -1; } catch (InternalCompilerError const& exception) { SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Internal compiler error", compiler); return -1; } catch (Exception const& exception) { cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl; return -1; } catch (...) { cerr << "Unknown exception during compilation." << endl; return -1; } cout << "Syntax trees:" << endl << endl; for (auto const& sourceCode: sourceCodes) { cout << endl << "======= " << sourceCode.first << " =======" << endl; ASTPrinter printer(compiler.getAST(sourceCode.first), sourceCode.second); printer.print(cout); } vector<string> contracts = compiler.getContractNames(); cout << endl << "Contracts:" << endl; for (string const& contract: contracts) { cout << endl << "======= " << contract << " =======" << endl << "EVM assembly:" << endl; compiler.streamAssembly(cout, contract); cout << "Opcodes:" << endl << eth::disassemble(compiler.getBytecode(contract)) << endl << "Binary: " << toHex(compiler.getBytecode(contract)) << endl << "Interface specification: " << compiler.getJsonDocumentation(contract, DocumentationType::ABI_INTERFACE) << endl << "Natspec user documentation: " << compiler.getJsonDocumentation(contract, DocumentationType::NATSPEC_USER) << endl << "Natspec developer documentation: " << compiler.getJsonDocumentation(contract, DocumentationType::NATSPEC_DEV) << endl; } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2012-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/system.h> #include <util/time.h> #include <validation.h> #include <atomic> #include <checkqueue.h> #include <condition_variable> #include <mutex> #include <test/util/setup_common.h> #include <thread> #include <vector> #include <boost/test/unit_test.hpp> #include <memory> #include <unordered_set> // BasicTestingSetup not sufficient because nScriptCheckThreads is not set // otherwise. BOOST_FIXTURE_TEST_SUITE(checkqueue_tests, TestingSetup) static const unsigned int QUEUE_BATCH_SIZE = 128; struct FakeCheck { bool operator()() { return true; } void swap(FakeCheck &x){}; }; struct FakeCheckCheckCompletion { static std::atomic<size_t> n_calls; bool operator()() { n_calls.fetch_add(1, std::memory_order_relaxed); return true; } void swap(FakeCheckCheckCompletion &x){}; }; struct FailingCheck { bool fails; FailingCheck(bool _fails) : fails(_fails){}; FailingCheck() : fails(true){}; bool operator()() { return !fails; } void swap(FailingCheck &x) { std::swap(fails, x.fails); }; }; struct UniqueCheck { static std::mutex m; static std::unordered_multiset<size_t> results; size_t check_id; UniqueCheck(size_t check_id_in) : check_id(check_id_in){}; UniqueCheck() : check_id(0){}; bool operator()() { std::lock_guard<std::mutex> l(m); results.insert(check_id); return true; } void swap(UniqueCheck &x) { std::swap(x.check_id, check_id); }; }; struct MemoryCheck { static std::atomic<size_t> fake_allocated_memory; bool b{false}; bool operator()() { return true; } MemoryCheck(){}; MemoryCheck(const MemoryCheck &x) { // We have to do this to make sure that destructor calls are paired // // Really, copy constructor should be deletable, but CCheckQueue breaks // if it is deleted because of internal push_back. fake_allocated_memory.fetch_add(b, std::memory_order_relaxed); }; MemoryCheck(bool b_) : b(b_) { fake_allocated_memory.fetch_add(b, std::memory_order_relaxed); }; ~MemoryCheck() { fake_allocated_memory.fetch_sub(b, std::memory_order_relaxed); }; void swap(MemoryCheck &x) { std::swap(b, x.b); }; }; struct FrozenCleanupCheck { static std::atomic<uint64_t> nFrozen; static std::condition_variable cv; static std::mutex m; // Freezing can't be the default initialized behavior given how the queue // swaps in default initialized Checks. bool should_freeze{false}; bool operator()() { return true; } FrozenCleanupCheck() {} ~FrozenCleanupCheck() { if (should_freeze) { std::unique_lock<std::mutex> l(m); nFrozen.store(1, std::memory_order_relaxed); cv.notify_one(); cv.wait( l, [] { return nFrozen.load(std::memory_order_relaxed) == 0; }); } } void swap(FrozenCleanupCheck &x) { std::swap(should_freeze, x.should_freeze); }; }; // Static Allocations std::mutex FrozenCleanupCheck::m{}; std::atomic<uint64_t> FrozenCleanupCheck::nFrozen{0}; std::condition_variable FrozenCleanupCheck::cv{}; std::mutex UniqueCheck::m; std::unordered_multiset<size_t> UniqueCheck::results; std::atomic<size_t> FakeCheckCheckCompletion::n_calls{0}; std::atomic<size_t> MemoryCheck::fake_allocated_memory{0}; // Queue Typedefs typedef CCheckQueue<FakeCheckCheckCompletion> Correct_Queue; typedef CCheckQueue<FakeCheck> Standard_Queue; typedef CCheckQueue<FailingCheck> Failing_Queue; typedef CCheckQueue<UniqueCheck> Unique_Queue; typedef CCheckQueue<MemoryCheck> Memory_Queue; typedef CCheckQueue<FrozenCleanupCheck> FrozenCleanup_Queue; /** This test case checks that the CCheckQueue works properly * with each specified size_t Checks pushed. */ static void Correct_Queue_range(std::vector<size_t> range) { auto small_queue = std::make_unique<Correct_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&] { small_queue->Thread(); }); } // Make vChecks here to save on malloc (this test can be slow...) std::vector<FakeCheckCheckCompletion> vChecks; for (const size_t i : range) { size_t total = i; FakeCheckCheckCompletion::n_calls = 0; CCheckQueueControl<FakeCheckCheckCompletion> control(small_queue.get()); while (total) { vChecks.resize(std::min(total, (size_t)InsecureRandRange(10))); total -= vChecks.size(); control.Add(vChecks); } BOOST_REQUIRE(control.Wait()); if (FakeCheckCheckCompletion::n_calls != i) { BOOST_REQUIRE_EQUAL(FakeCheckCheckCompletion::n_calls, i); } } tg.interrupt_all(); tg.join_all(); } /** Test that 0 checks is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Zero) { std::vector<size_t> range; range.push_back((size_t)0); Correct_Queue_range(range); } /** Test that 1 check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_One) { std::vector<size_t> range; range.push_back((size_t)1); Correct_Queue_range(range); } /** Test that MAX check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Max) { std::vector<size_t> range; range.push_back(100000); Correct_Queue_range(range); } /** Test that random numbers of checks are correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Random) { std::vector<size_t> range; range.reserve(100000 / 1000); for (size_t i = 2; i < 100000; i += std::max((size_t)1, (size_t)InsecureRandRange(std::min( (size_t)1000, ((size_t)100000) - i)))) { range.push_back(i); } Correct_Queue_range(range); } /** Test that failing checks are caught */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Catches_Failure) { auto fail_queue = std::make_unique<Failing_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&] { fail_queue->Thread(); }); } for (size_t i = 0; i < 1001; ++i) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); size_t remaining = i; while (remaining) { size_t r = InsecureRandRange(10); std::vector<FailingCheck> vChecks; vChecks.reserve(r); for (size_t k = 0; k < r && remaining; k++, remaining--) { vChecks.emplace_back(remaining == 1); } control.Add(vChecks); } bool success = control.Wait(); if (i > 0) { BOOST_REQUIRE(!success); } else if (i == 0) { BOOST_REQUIRE(success); } } tg.interrupt_all(); tg.join_all(); } // Test that a block validation which fails does not interfere with // future blocks, ie, the bad state is cleared. BOOST_AUTO_TEST_CASE(test_CheckQueue_Recovers_From_Failure) { auto fail_queue = std::make_unique<Failing_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&] { fail_queue->Thread(); }); } for (auto times = 0; times < 10; ++times) { for (const bool end_fails : {true, false}) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); { std::vector<FailingCheck> vChecks; vChecks.resize(100, false); vChecks[99] = end_fails; control.Add(vChecks); } bool r = control.Wait(); BOOST_REQUIRE(r != end_fails); } } tg.interrupt_all(); tg.join_all(); } // Test that unique checks are actually all called individually, rather than // just one check being called repeatedly. Test that checks are not called // more than once as well BOOST_AUTO_TEST_CASE(test_CheckQueue_UniqueCheck) { auto queue = std::make_unique<Unique_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&] { queue->Thread(); }); } size_t COUNT = 100000; size_t total = COUNT; { CCheckQueueControl<UniqueCheck> control(queue.get()); while (total) { size_t r = InsecureRandRange(10); std::vector<UniqueCheck> vChecks; for (size_t k = 0; k < r && total; k++) { vChecks.emplace_back(--total); } control.Add(vChecks); } } bool r = true; BOOST_REQUIRE_EQUAL(UniqueCheck::results.size(), COUNT); for (size_t i = 0; i < COUNT; ++i) { r = r && UniqueCheck::results.count(i) == 1; } BOOST_REQUIRE(r); tg.interrupt_all(); tg.join_all(); } // Test that blocks which might allocate lots of memory free their memory // aggressively. // // This test attempts to catch a pathological case where by lazily freeing // checks might mean leaving a check un-swapped out, and decreasing by 1 each // time could leave the data hanging across a sequence of blocks. BOOST_AUTO_TEST_CASE(test_CheckQueue_Memory) { auto queue = std::make_unique<Memory_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&] { queue->Thread(); }); } for (size_t i = 0; i < 1000; ++i) { size_t total = i; { CCheckQueueControl<MemoryCheck> control(queue.get()); while (total) { size_t r = InsecureRandRange(10); std::vector<MemoryCheck> vChecks; for (size_t k = 0; k < r && total; k++) { total--; // Each iteration leaves data at the front, back, and middle // to catch any sort of deallocation failure vChecks.emplace_back(total == 0 || total == i || total == i / 2); } control.Add(vChecks); } } BOOST_REQUIRE_EQUAL(MemoryCheck::fake_allocated_memory, 0U); } tg.interrupt_all(); tg.join_all(); } // Test that a new verification cannot occur until all checks // have been destructed BOOST_AUTO_TEST_CASE(test_CheckQueue_FrozenCleanup) { auto queue = std::make_unique<FrozenCleanup_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; bool fails = false; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&] { queue->Thread(); }); } std::thread t0([&]() { CCheckQueueControl<FrozenCleanupCheck> control(queue.get()); std::vector<FrozenCleanupCheck> vChecks(1); // Freezing can't be the default initialized behavior given how the // queue // swaps in default initialized Checks (otherwise freezing destructor // would get called twice). vChecks[0].should_freeze = true; control.Add(vChecks); // Hangs here bool waitResult = control.Wait(); assert(waitResult); }); { std::unique_lock<std::mutex> l(FrozenCleanupCheck::m); // Wait until the queue has finished all jobs and frozen FrozenCleanupCheck::cv.wait( l, []() { return FrozenCleanupCheck::nFrozen == 1; }); } // Try to get control of the queue a bunch of times for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } { // Unfreeze (we need lock n case of spurious wakeup) std::unique_lock<std::mutex> l(FrozenCleanupCheck::m); FrozenCleanupCheck::nFrozen = 0; } // Awaken frozen destructor FrozenCleanupCheck::cv.notify_one(); // Wait for control to finish t0.join(); tg.interrupt_all(); tg.join_all(); BOOST_REQUIRE(!fails); } /** Test that CCheckQueueControl is threadsafe */ BOOST_AUTO_TEST_CASE(test_CheckQueueControl_Locks) { auto queue = std::make_unique<Standard_Queue>(QUEUE_BATCH_SIZE); { boost::thread_group tg; std::atomic<int> nThreads{0}; std::atomic<int> fails{0}; for (size_t i = 0; i < 3; ++i) { tg.create_thread([&] { CCheckQueueControl<FakeCheck> control(queue.get()); // While sleeping, no other thread should execute to this point auto observed = ++nThreads; UninterruptibleSleep(std::chrono::milliseconds{10}); fails += observed != nThreads; }); } tg.join_all(); BOOST_REQUIRE_EQUAL(fails, 0); } { boost::thread_group tg; std::mutex m; std::condition_variable cv; bool has_lock{false}; bool has_tried{false}; bool done{false}; bool done_ack{false}; { std::unique_lock<std::mutex> l(m); tg.create_thread([&] { CCheckQueueControl<FakeCheck> control(queue.get()); std::unique_lock<std::mutex> ll(m); has_lock = true; cv.notify_one(); cv.wait(ll, [&] { return has_tried; }); done = true; cv.notify_one(); // Wait until the done is acknowledged // cv.wait(ll, [&] { return done_ack; }); }); // Wait for thread to get the lock cv.wait(l, [&]() { return has_lock; }); bool fails = false; for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } has_tried = true; cv.notify_one(); cv.wait(l, [&]() { return done; }); // Acknowledge the done done_ack = true; cv.notify_one(); BOOST_REQUIRE(!fails); } tg.join_all(); } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>[backport#17342][tests] Don't use nScriptCheckThreads in the checkqueue_tests<commit_after>// Copyright (c) 2012-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/system.h> #include <util/time.h> #include <atomic> #include <checkqueue.h> #include <condition_variable> #include <mutex> #include <test/util/setup_common.h> #include <thread> #include <vector> #include <boost/test/unit_test.hpp> #include <memory> #include <unordered_set> BOOST_FIXTURE_TEST_SUITE(checkqueue_tests, TestingSetup) static const unsigned int QUEUE_BATCH_SIZE = 128; static const int SCRIPT_CHECK_THREADS = 3; struct FakeCheck { bool operator()() { return true; } void swap(FakeCheck &x){}; }; struct FakeCheckCheckCompletion { static std::atomic<size_t> n_calls; bool operator()() { n_calls.fetch_add(1, std::memory_order_relaxed); return true; } void swap(FakeCheckCheckCompletion &x){}; }; struct FailingCheck { bool fails; FailingCheck(bool _fails) : fails(_fails){}; FailingCheck() : fails(true){}; bool operator()() { return !fails; } void swap(FailingCheck &x) { std::swap(fails, x.fails); }; }; struct UniqueCheck { static std::mutex m; static std::unordered_multiset<size_t> results; size_t check_id; UniqueCheck(size_t check_id_in) : check_id(check_id_in){}; UniqueCheck() : check_id(0){}; bool operator()() { std::lock_guard<std::mutex> l(m); results.insert(check_id); return true; } void swap(UniqueCheck &x) { std::swap(x.check_id, check_id); }; }; struct MemoryCheck { static std::atomic<size_t> fake_allocated_memory; bool b{false}; bool operator()() { return true; } MemoryCheck(){}; MemoryCheck(const MemoryCheck &x) { // We have to do this to make sure that destructor calls are paired // // Really, copy constructor should be deletable, but CCheckQueue breaks // if it is deleted because of internal push_back. fake_allocated_memory.fetch_add(b, std::memory_order_relaxed); }; MemoryCheck(bool b_) : b(b_) { fake_allocated_memory.fetch_add(b, std::memory_order_relaxed); }; ~MemoryCheck() { fake_allocated_memory.fetch_sub(b, std::memory_order_relaxed); }; void swap(MemoryCheck &x) { std::swap(b, x.b); }; }; struct FrozenCleanupCheck { static std::atomic<uint64_t> nFrozen; static std::condition_variable cv; static std::mutex m; // Freezing can't be the default initialized behavior given how the queue // swaps in default initialized Checks. bool should_freeze{false}; bool operator()() { return true; } FrozenCleanupCheck() {} ~FrozenCleanupCheck() { if (should_freeze) { std::unique_lock<std::mutex> l(m); nFrozen.store(1, std::memory_order_relaxed); cv.notify_one(); cv.wait( l, [] { return nFrozen.load(std::memory_order_relaxed) == 0; }); } } void swap(FrozenCleanupCheck &x) { std::swap(should_freeze, x.should_freeze); }; }; // Static Allocations std::mutex FrozenCleanupCheck::m{}; std::atomic<uint64_t> FrozenCleanupCheck::nFrozen{0}; std::condition_variable FrozenCleanupCheck::cv{}; std::mutex UniqueCheck::m; std::unordered_multiset<size_t> UniqueCheck::results; std::atomic<size_t> FakeCheckCheckCompletion::n_calls{0}; std::atomic<size_t> MemoryCheck::fake_allocated_memory{0}; // Queue Typedefs typedef CCheckQueue<FakeCheckCheckCompletion> Correct_Queue; typedef CCheckQueue<FakeCheck> Standard_Queue; typedef CCheckQueue<FailingCheck> Failing_Queue; typedef CCheckQueue<UniqueCheck> Unique_Queue; typedef CCheckQueue<MemoryCheck> Memory_Queue; typedef CCheckQueue<FrozenCleanupCheck> FrozenCleanup_Queue; /** This test case checks that the CCheckQueue works properly * with each specified size_t Checks pushed. */ static void Correct_Queue_range(std::vector<size_t> range) { auto small_queue = std::make_unique<Correct_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < SCRIPT_CHECK_THREADS; ++x) { tg.create_thread([&] { small_queue->Thread(); }); } // Make vChecks here to save on malloc (this test can be slow...) std::vector<FakeCheckCheckCompletion> vChecks; for (const size_t i : range) { size_t total = i; FakeCheckCheckCompletion::n_calls = 0; CCheckQueueControl<FakeCheckCheckCompletion> control(small_queue.get()); while (total) { vChecks.resize(std::min(total, (size_t)InsecureRandRange(10))); total -= vChecks.size(); control.Add(vChecks); } BOOST_REQUIRE(control.Wait()); if (FakeCheckCheckCompletion::n_calls != i) { BOOST_REQUIRE_EQUAL(FakeCheckCheckCompletion::n_calls, i); } } tg.interrupt_all(); tg.join_all(); } /** Test that 0 checks is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Zero) { std::vector<size_t> range; range.push_back((size_t)0); Correct_Queue_range(range); } /** Test that 1 check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_One) { std::vector<size_t> range; range.push_back((size_t)1); Correct_Queue_range(range); } /** Test that MAX check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Max) { std::vector<size_t> range; range.push_back(100000); Correct_Queue_range(range); } /** Test that random numbers of checks are correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Random) { std::vector<size_t> range; range.reserve(100000 / 1000); for (size_t i = 2; i < 100000; i += std::max((size_t)1, (size_t)InsecureRandRange(std::min( (size_t)1000, ((size_t)100000) - i)))) { range.push_back(i); } Correct_Queue_range(range); } /** Test that failing checks are caught */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Catches_Failure) { auto fail_queue = std::make_unique<Failing_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < SCRIPT_CHECK_THREADS; ++x) { tg.create_thread([&] { fail_queue->Thread(); }); } for (size_t i = 0; i < 1001; ++i) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); size_t remaining = i; while (remaining) { size_t r = InsecureRandRange(10); std::vector<FailingCheck> vChecks; vChecks.reserve(r); for (size_t k = 0; k < r && remaining; k++, remaining--) { vChecks.emplace_back(remaining == 1); } control.Add(vChecks); } bool success = control.Wait(); if (i > 0) { BOOST_REQUIRE(!success); } else if (i == 0) { BOOST_REQUIRE(success); } } tg.interrupt_all(); tg.join_all(); } // Test that a block validation which fails does not interfere with // future blocks, ie, the bad state is cleared. BOOST_AUTO_TEST_CASE(test_CheckQueue_Recovers_From_Failure) { auto fail_queue = std::make_unique<Failing_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < SCRIPT_CHECK_THREADS; ++x) { tg.create_thread([&] { fail_queue->Thread(); }); } for (auto times = 0; times < 10; ++times) { for (const bool end_fails : {true, false}) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); { std::vector<FailingCheck> vChecks; vChecks.resize(100, false); vChecks[99] = end_fails; control.Add(vChecks); } bool r = control.Wait(); BOOST_REQUIRE(r != end_fails); } } tg.interrupt_all(); tg.join_all(); } // Test that unique checks are actually all called individually, rather than // just one check being called repeatedly. Test that checks are not called // more than once as well BOOST_AUTO_TEST_CASE(test_CheckQueue_UniqueCheck) { auto queue = std::make_unique<Unique_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < SCRIPT_CHECK_THREADS; ++x) { tg.create_thread([&] { queue->Thread(); }); } size_t COUNT = 100000; size_t total = COUNT; { CCheckQueueControl<UniqueCheck> control(queue.get()); while (total) { size_t r = InsecureRandRange(10); std::vector<UniqueCheck> vChecks; for (size_t k = 0; k < r && total; k++) { vChecks.emplace_back(--total); } control.Add(vChecks); } } bool r = true; BOOST_REQUIRE_EQUAL(UniqueCheck::results.size(), COUNT); for (size_t i = 0; i < COUNT; ++i) { r = r && UniqueCheck::results.count(i) == 1; } BOOST_REQUIRE(r); tg.interrupt_all(); tg.join_all(); } // Test that blocks which might allocate lots of memory free their memory // aggressively. // // This test attempts to catch a pathological case where by lazily freeing // checks might mean leaving a check un-swapped out, and decreasing by 1 each // time could leave the data hanging across a sequence of blocks. BOOST_AUTO_TEST_CASE(test_CheckQueue_Memory) { auto queue = std::make_unique<Memory_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; for (auto x = 0; x < SCRIPT_CHECK_THREADS; ++x) { tg.create_thread([&] { queue->Thread(); }); } for (size_t i = 0; i < 1000; ++i) { size_t total = i; { CCheckQueueControl<MemoryCheck> control(queue.get()); while (total) { size_t r = InsecureRandRange(10); std::vector<MemoryCheck> vChecks; for (size_t k = 0; k < r && total; k++) { total--; // Each iteration leaves data at the front, back, and middle // to catch any sort of deallocation failure vChecks.emplace_back(total == 0 || total == i || total == i / 2); } control.Add(vChecks); } } BOOST_REQUIRE_EQUAL(MemoryCheck::fake_allocated_memory, 0U); } tg.interrupt_all(); tg.join_all(); } // Test that a new verification cannot occur until all checks // have been destructed BOOST_AUTO_TEST_CASE(test_CheckQueue_FrozenCleanup) { auto queue = std::make_unique<FrozenCleanup_Queue>(QUEUE_BATCH_SIZE); boost::thread_group tg; bool fails = false; for (auto x = 0; x < SCRIPT_CHECK_THREADS; ++x) { tg.create_thread([&] { queue->Thread(); }); } std::thread t0([&]() { CCheckQueueControl<FrozenCleanupCheck> control(queue.get()); std::vector<FrozenCleanupCheck> vChecks(1); // Freezing can't be the default initialized behavior given how the // queue // swaps in default initialized Checks (otherwise freezing destructor // would get called twice). vChecks[0].should_freeze = true; control.Add(vChecks); // Hangs here bool waitResult = control.Wait(); assert(waitResult); }); { std::unique_lock<std::mutex> l(FrozenCleanupCheck::m); // Wait until the queue has finished all jobs and frozen FrozenCleanupCheck::cv.wait( l, []() { return FrozenCleanupCheck::nFrozen == 1; }); } // Try to get control of the queue a bunch of times for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } { // Unfreeze (we need lock n case of spurious wakeup) std::unique_lock<std::mutex> l(FrozenCleanupCheck::m); FrozenCleanupCheck::nFrozen = 0; } // Awaken frozen destructor FrozenCleanupCheck::cv.notify_one(); // Wait for control to finish t0.join(); tg.interrupt_all(); tg.join_all(); BOOST_REQUIRE(!fails); } /** Test that CCheckQueueControl is threadsafe */ BOOST_AUTO_TEST_CASE(test_CheckQueueControl_Locks) { auto queue = std::make_unique<Standard_Queue>(QUEUE_BATCH_SIZE); { boost::thread_group tg; std::atomic<int> nThreads{0}; std::atomic<int> fails{0}; for (size_t i = 0; i < 3; ++i) { tg.create_thread([&] { CCheckQueueControl<FakeCheck> control(queue.get()); // While sleeping, no other thread should execute to this point auto observed = ++nThreads; UninterruptibleSleep(std::chrono::milliseconds{10}); fails += observed != nThreads; }); } tg.join_all(); BOOST_REQUIRE_EQUAL(fails, 0); } { boost::thread_group tg; std::mutex m; std::condition_variable cv; bool has_lock{false}; bool has_tried{false}; bool done{false}; bool done_ack{false}; { std::unique_lock<std::mutex> l(m); tg.create_thread([&] { CCheckQueueControl<FakeCheck> control(queue.get()); std::unique_lock<std::mutex> ll(m); has_lock = true; cv.notify_one(); cv.wait(ll, [&] { return has_tried; }); done = true; cv.notify_one(); // Wait until the done is acknowledged // cv.wait(ll, [&] { return done_ack; }); }); // Wait for thread to get the lock cv.wait(l, [&]() { return has_lock; }); bool fails = false; for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } has_tried = true; cv.notify_one(); cv.wait(l, [&]() { return done; }); // Acknowledge the done done_ack = true; cv.notify_one(); BOOST_REQUIRE(!fails); } tg.join_all(); } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////// // $Id: osdep.cc,v 1.12 2003/01/10 22:32:44 cbothamy Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // osdep.cc // // Provide definition of library functions that are missing on various // systems. The only reason this is a .cc file rather than a .c file // is so that it can include bochs.h. Bochs.h includes all the required // system headers, with appropriate #ifdefs for different compilers and // platforms. // #include "bochs.h" ////////////////////////////////////////////////////////////////////// // Missing library functions. These should work on any platform // that needs them. ////////////////////////////////////////////////////////////////////// #if !BX_HAVE_SNPRINTF /* XXX use real snprintf */ /* if they don't have snprintf, just use sprintf */ int bx_snprintf (char *s, size_t maxlen, const char *format, ...) { va_list arg; int done; va_start (arg, format); done = vsprintf (s, format, arg); va_end (arg); return done; } #endif /* !BX_HAVE_SNPRINTF */ #if (!BX_HAVE_STRTOULL && !BX_HAVE_STRTOUQ) /* taken from glibc-2.2.2: strtod.c, and stripped down a lot. There are still a few leftover references to decimal points and exponents, but it works for bases 10 and 16 */ #define RETURN(val,end) \ do { if (endptr != NULL) *endptr = (char *) (end); \ return val; } while (0) Bit64u bx_strtoull (const char *nptr, char **endptr, int baseignore) { int negative; /* The sign of the number. */ int exponent; /* Exponent of the number. */ /* Numbers starting `0X' or `0x' have to be processed with base 16. */ int base = 10; /* Number of bits currently in result value. */ int bits; /* Running pointer after the last character processed in the string. */ const char *cp, *tp; /* Start of significant part of the number. */ const char *startp, *start_of_digits; /* Total number of digit and number of digits in integer part. */ int dig_no; /* Contains the last character read. */ char c; Bit64s n = 0; char const *p; /* Prepare number representation. */ exponent = 0; negative = 0; bits = 0; /* Parse string to get maximal legal prefix. We need the number of characters of the integer part, the fractional part and the exponent. */ cp = nptr - 1; /* Ignore leading white space. */ do c = *++cp; while (isspace (c)); /* Get sign of the result. */ if (c == '-') { negative = 1; c = *++cp; } else if (c == '+') c = *++cp; if (c < '0' || c > '9') { /* It is really a text we do not recognize. */ RETURN (0, nptr); } /* First look whether we are faced with a hexadecimal number. */ if (c == '0' && tolower (cp[1]) == 'x') { /* Okay, it is a hexa-decimal number. Remember this and skip the characters. BTW: hexadecimal numbers must not be grouped. */ base = 16; cp += 2; c = *cp; } /* Record the start of the digits, in case we will check their grouping. */ start_of_digits = startp = cp; /* Ignore leading zeroes. This helps us to avoid useless computations. */ while (c == '0') c = *++cp; /* If no other digit but a '0' is found the result is 0.0. Return current read pointer. */ if ((c < '0' || c > '9') && (base == 16 && (c < tolower ('a') || c > tolower ('f'))) && (base == 16 && (cp == start_of_digits || tolower (c) != 'p')) && (base != 16 && tolower (c) != 'e')) { tp = start_of_digits; /* If TP is at the start of the digits, there was no correctly grouped prefix of the string; so no number found. */ RETURN (0, tp == start_of_digits ? (base == 16 ? cp - 1 : nptr) : tp); } /* Remember first significant digit and read following characters until the decimal point, exponent character or any non-FP number character. */ startp = cp; dig_no = 0; while (1) { if ((c >= '0' && c <= '9') || (base == 16 && tolower (c) >= 'a' && tolower (c) <= 'f')) ++dig_no; else break; c = *++cp; } /* The whole string is parsed. Store the address of the next character. */ if (endptr) *endptr = (char *) cp; if (dig_no == 0) return 0; for (p=start_of_digits; p!=cp; p++) { n = n * (Bit64s)base; c = tolower (*p); c = (c >= 'a') ? (10+c-'a') : c-'0'; n = n + (Bit64s)c; //printf ("after shifting in digit %c, n is %lld\n", *p, n); } return negative? -n : n; } #endif /* !BX_HAVE_STRTOULL */ #if BX_TEST_STRTOULL_MAIN /* test driver for strtoull. Do not compile by default. */ int main (int argc, char **argv) { char buf[256], *endbuf; long l; Bit64s ll; while (1) { printf ("Enter a long int: "); gets (buf); l = strtoul (buf, &endbuf, 10); printf ("As a long, %ld\n", l); printf ("Endbuf is at buf[%d]\n", endbuf-buf); ll = bx_strtoull (buf, &endbuf, 10); printf ("As a long long, %lld\n", ll); printf ("Endbuf is at buf[%d]\n", endbuf-buf); } return 0; } #endif /* BX_TEST_STRTOULL_MAIN */ #if !BX_HAVE_STRDUP /* XXX use real strdup */ char *bx_strdup(const char *str) { char *temp; temp = (char*)malloc(strlen(str)+1); sprintf(temp, "%s", str); return temp; // Well, I'm sure this isn't how strdup is REALLY implemented, // but it works... } #endif /* !BX_HAVE_STRDUP */ #if !BX_HAVE_STRREV char *bx_strrev(char *str) { char *p1, *p2; if (! str || ! *str) return str; for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2) { *p1 ^= *p2; *p2 ^= *p1; *p1 ^= *p2; } return str; } #endif /* !BX_HAVE_STRREV */ ////////////////////////////////////////////////////////////////////// // Missing library functions, implemented for MacOS only ////////////////////////////////////////////////////////////////////// #if BX_WITH_MACOS // these functions are part of MacBochs. They are not intended to be // portable! #include <Devices.h> #include <Files.h> #include <Disks.h> int fd_read(char *buffer, Bit32u offset, Bit32u bytes) { OSErr err; IOParam param; param.ioRefNum=-5; // Refnum of the floppy disk driver param.ioVRefNum=1; param.ioPosMode=fsFromStart; param.ioPosOffset=offset; param.ioBuffer=buffer; param.ioReqCount=bytes; err = PBReadSync((union ParamBlockRec *)(&param)); return param.ioActCount; } int fd_write(char *buffer, Bit32u offset, Bit32u bytes) { OSErr err; IOParam param; param.ioRefNum=-5; // Refnum of the floppy disk driver param.ioVRefNum=1; param.ioPosMode=fsFromStart; param.ioPosOffset=offset; param.ioBuffer=buffer; param.ioReqCount=bytes; err = PBWriteSync((union ParamBlockRec *)(&param)); return param.ioActCount; } int fd_stat(struct stat *buf) { OSErr err; DrvSts status; int result; result = 0; err = DriveStatus(1, &status); if (status.diskInPlace <1 || status.diskInPlace > 2) result = -1; buf->st_mode = S_IFCHR; return result; } #endif /* BX_WITH_MACOS */ ////////////////////////////////////////////////////////////////////// // New functions to replace library functions // with OS-independent versions ////////////////////////////////////////////////////////////////////// #if BX_HAVE_REALTIME_USEC # if BX_HAVE_GETTIMEOFDAY Bit64u bx_get_realtime64_usec (void) { timeval thetime; gettimeofday(&thetime,0); Bit64u mytime; mytime=(Bit64u)thetime.tv_sec*(Bit64u)1000000+(Bit64u)thetime.tv_usec; return mytime; } # else # if BX_WITH_WIN32 Bit64u last_realtime64_top = 0; Bit64u last_realtime64_bottom = 0; Bit64u bx_get_realtime64_usec (void) { Bit64u new_bottom = ((Bit64u) GetTickCount()) & BX_CONST64(0x0FFFFFFFF); if(new_bottom < last_realtime64_bottom) { last_realtime64_top += BX_CONST64(0x0000000100000000); } last_realtime64_bottom = new_bottom; Bit64u interim_realtime64 = (last_realtime64_top & BX_CONST64(0xFFFFFFFF00000000)) | (new_bottom & BX_CONST64(0x00000000FFFFFFFF)); return interim_realtime64*(BX_CONST64(1000)); } # endif # endif #endif <commit_msg>- replaced BX_WITH_WIN32 by the platform symbol WIN32<commit_after>///////////////////////////////////////////////////////////////////////// // $Id: osdep.cc,v 1.13 2003/03/11 17:30:20 vruppert Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // osdep.cc // // Provide definition of library functions that are missing on various // systems. The only reason this is a .cc file rather than a .c file // is so that it can include bochs.h. Bochs.h includes all the required // system headers, with appropriate #ifdefs for different compilers and // platforms. // #include "bochs.h" ////////////////////////////////////////////////////////////////////// // Missing library functions. These should work on any platform // that needs them. ////////////////////////////////////////////////////////////////////// #if !BX_HAVE_SNPRINTF /* XXX use real snprintf */ /* if they don't have snprintf, just use sprintf */ int bx_snprintf (char *s, size_t maxlen, const char *format, ...) { va_list arg; int done; va_start (arg, format); done = vsprintf (s, format, arg); va_end (arg); return done; } #endif /* !BX_HAVE_SNPRINTF */ #if (!BX_HAVE_STRTOULL && !BX_HAVE_STRTOUQ) /* taken from glibc-2.2.2: strtod.c, and stripped down a lot. There are still a few leftover references to decimal points and exponents, but it works for bases 10 and 16 */ #define RETURN(val,end) \ do { if (endptr != NULL) *endptr = (char *) (end); \ return val; } while (0) Bit64u bx_strtoull (const char *nptr, char **endptr, int baseignore) { int negative; /* The sign of the number. */ int exponent; /* Exponent of the number. */ /* Numbers starting `0X' or `0x' have to be processed with base 16. */ int base = 10; /* Number of bits currently in result value. */ int bits; /* Running pointer after the last character processed in the string. */ const char *cp, *tp; /* Start of significant part of the number. */ const char *startp, *start_of_digits; /* Total number of digit and number of digits in integer part. */ int dig_no; /* Contains the last character read. */ char c; Bit64s n = 0; char const *p; /* Prepare number representation. */ exponent = 0; negative = 0; bits = 0; /* Parse string to get maximal legal prefix. We need the number of characters of the integer part, the fractional part and the exponent. */ cp = nptr - 1; /* Ignore leading white space. */ do c = *++cp; while (isspace (c)); /* Get sign of the result. */ if (c == '-') { negative = 1; c = *++cp; } else if (c == '+') c = *++cp; if (c < '0' || c > '9') { /* It is really a text we do not recognize. */ RETURN (0, nptr); } /* First look whether we are faced with a hexadecimal number. */ if (c == '0' && tolower (cp[1]) == 'x') { /* Okay, it is a hexa-decimal number. Remember this and skip the characters. BTW: hexadecimal numbers must not be grouped. */ base = 16; cp += 2; c = *cp; } /* Record the start of the digits, in case we will check their grouping. */ start_of_digits = startp = cp; /* Ignore leading zeroes. This helps us to avoid useless computations. */ while (c == '0') c = *++cp; /* If no other digit but a '0' is found the result is 0.0. Return current read pointer. */ if ((c < '0' || c > '9') && (base == 16 && (c < tolower ('a') || c > tolower ('f'))) && (base == 16 && (cp == start_of_digits || tolower (c) != 'p')) && (base != 16 && tolower (c) != 'e')) { tp = start_of_digits; /* If TP is at the start of the digits, there was no correctly grouped prefix of the string; so no number found. */ RETURN (0, tp == start_of_digits ? (base == 16 ? cp - 1 : nptr) : tp); } /* Remember first significant digit and read following characters until the decimal point, exponent character or any non-FP number character. */ startp = cp; dig_no = 0; while (1) { if ((c >= '0' && c <= '9') || (base == 16 && tolower (c) >= 'a' && tolower (c) <= 'f')) ++dig_no; else break; c = *++cp; } /* The whole string is parsed. Store the address of the next character. */ if (endptr) *endptr = (char *) cp; if (dig_no == 0) return 0; for (p=start_of_digits; p!=cp; p++) { n = n * (Bit64s)base; c = tolower (*p); c = (c >= 'a') ? (10+c-'a') : c-'0'; n = n + (Bit64s)c; //printf ("after shifting in digit %c, n is %lld\n", *p, n); } return negative? -n : n; } #endif /* !BX_HAVE_STRTOULL */ #if BX_TEST_STRTOULL_MAIN /* test driver for strtoull. Do not compile by default. */ int main (int argc, char **argv) { char buf[256], *endbuf; long l; Bit64s ll; while (1) { printf ("Enter a long int: "); gets (buf); l = strtoul (buf, &endbuf, 10); printf ("As a long, %ld\n", l); printf ("Endbuf is at buf[%d]\n", endbuf-buf); ll = bx_strtoull (buf, &endbuf, 10); printf ("As a long long, %lld\n", ll); printf ("Endbuf is at buf[%d]\n", endbuf-buf); } return 0; } #endif /* BX_TEST_STRTOULL_MAIN */ #if !BX_HAVE_STRDUP /* XXX use real strdup */ char *bx_strdup(const char *str) { char *temp; temp = (char*)malloc(strlen(str)+1); sprintf(temp, "%s", str); return temp; // Well, I'm sure this isn't how strdup is REALLY implemented, // but it works... } #endif /* !BX_HAVE_STRDUP */ #if !BX_HAVE_STRREV char *bx_strrev(char *str) { char *p1, *p2; if (! str || ! *str) return str; for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2) { *p1 ^= *p2; *p2 ^= *p1; *p1 ^= *p2; } return str; } #endif /* !BX_HAVE_STRREV */ ////////////////////////////////////////////////////////////////////// // Missing library functions, implemented for MacOS only ////////////////////////////////////////////////////////////////////// #if BX_WITH_MACOS // these functions are part of MacBochs. They are not intended to be // portable! #include <Devices.h> #include <Files.h> #include <Disks.h> int fd_read(char *buffer, Bit32u offset, Bit32u bytes) { OSErr err; IOParam param; param.ioRefNum=-5; // Refnum of the floppy disk driver param.ioVRefNum=1; param.ioPosMode=fsFromStart; param.ioPosOffset=offset; param.ioBuffer=buffer; param.ioReqCount=bytes; err = PBReadSync((union ParamBlockRec *)(&param)); return param.ioActCount; } int fd_write(char *buffer, Bit32u offset, Bit32u bytes) { OSErr err; IOParam param; param.ioRefNum=-5; // Refnum of the floppy disk driver param.ioVRefNum=1; param.ioPosMode=fsFromStart; param.ioPosOffset=offset; param.ioBuffer=buffer; param.ioReqCount=bytes; err = PBWriteSync((union ParamBlockRec *)(&param)); return param.ioActCount; } int fd_stat(struct stat *buf) { OSErr err; DrvSts status; int result; result = 0; err = DriveStatus(1, &status); if (status.diskInPlace <1 || status.diskInPlace > 2) result = -1; buf->st_mode = S_IFCHR; return result; } #endif /* BX_WITH_MACOS */ ////////////////////////////////////////////////////////////////////// // New functions to replace library functions // with OS-independent versions ////////////////////////////////////////////////////////////////////// #if BX_HAVE_REALTIME_USEC # if BX_HAVE_GETTIMEOFDAY Bit64u bx_get_realtime64_usec (void) { timeval thetime; gettimeofday(&thetime,0); Bit64u mytime; mytime=(Bit64u)thetime.tv_sec*(Bit64u)1000000+(Bit64u)thetime.tv_usec; return mytime; } # elif defined(WIN32) Bit64u last_realtime64_top = 0; Bit64u last_realtime64_bottom = 0; Bit64u bx_get_realtime64_usec (void) { Bit64u new_bottom = ((Bit64u) GetTickCount()) & BX_CONST64(0x0FFFFFFFF); if(new_bottom < last_realtime64_bottom) { last_realtime64_top += BX_CONST64(0x0000000100000000); } last_realtime64_bottom = new_bottom; Bit64u interim_realtime64 = (last_realtime64_top & BX_CONST64(0xFFFFFFFF00000000)) | (new_bottom & BX_CONST64(0x00000000FFFFFFFF)); return interim_realtime64*(BX_CONST64(1000)); } # endif #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ignoreKiKuFollowedBySa_ja_JP.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2004-09-08 16:46:13 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // prevent internal compiler error with MSVC6SP3 #include <utility> #define TRANSLITERATION_KiKuFollowedBySa_ja_JP #include <transliteration_Ignore.hxx> using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { OUString SAL_CALL ignoreKiKuFollowedBySa_ja_JP::folding( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset ) throw(RuntimeException) { // Create a string buffer which can hold nCount + 1 characters. // The reference count is 0 now. rtl_uString * newStr = x_rtl_uString_new_WithLength( nCount ); // defined in x_rtl_ustring.h sal_Unicode * dst = newStr->buffer; const sal_Unicode * src = inStr.getStr() + startPos; sal_Int32 *p = 0; sal_Int32 position = 0; if (useOffset) { // Allocate nCount length to offset argument. offset.realloc( nCount ); p = offset.getArray(); position = startPos; } // sal_Unicode previousChar = *src ++; sal_Unicode currentChar; // Translation while (-- nCount > 0) { currentChar = *src ++; // KU + Sa-So --> KI + Sa-So if (previousChar == 0x30AF ) { // KATAKANA LETTER KU if (0x30B5 <= currentChar && // KATAKANA LETTER SA currentChar <= 0x30BE) { // KATAKANA LETTER ZO if (useOffset) { *p ++ = position++; *p ++ = position++; } *dst ++ = 0x30AD; // KATAKANA LETTER KI *dst ++ = currentChar; previousChar = *src ++; nCount --; continue; } } if (useOffset) *p ++ = position++; *dst ++ = previousChar; previousChar = currentChar; } if (nCount == 0) { if (useOffset) *p = position; *dst ++ = previousChar; } *dst = (sal_Unicode) 0; newStr->length = sal_Int32(dst - newStr->buffer); if (useOffset) offset.realloc(newStr->length); return OUString( newStr ); // defined in rtl/usrting. The reference count is increased from 0 to 1. } } } } } <commit_msg>INTEGRATION: CWS ooo19126 (1.7.50); FILE MERGED 2005/09/05 17:47:55 rt 1.7.50.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ignoreKiKuFollowedBySa_ja_JP.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-07 17:28:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // prevent internal compiler error with MSVC6SP3 #include <utility> #define TRANSLITERATION_KiKuFollowedBySa_ja_JP #include <transliteration_Ignore.hxx> using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { OUString SAL_CALL ignoreKiKuFollowedBySa_ja_JP::folding( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset ) throw(RuntimeException) { // Create a string buffer which can hold nCount + 1 characters. // The reference count is 0 now. rtl_uString * newStr = x_rtl_uString_new_WithLength( nCount ); // defined in x_rtl_ustring.h sal_Unicode * dst = newStr->buffer; const sal_Unicode * src = inStr.getStr() + startPos; sal_Int32 *p = 0; sal_Int32 position = 0; if (useOffset) { // Allocate nCount length to offset argument. offset.realloc( nCount ); p = offset.getArray(); position = startPos; } // sal_Unicode previousChar = *src ++; sal_Unicode currentChar; // Translation while (-- nCount > 0) { currentChar = *src ++; // KU + Sa-So --> KI + Sa-So if (previousChar == 0x30AF ) { // KATAKANA LETTER KU if (0x30B5 <= currentChar && // KATAKANA LETTER SA currentChar <= 0x30BE) { // KATAKANA LETTER ZO if (useOffset) { *p ++ = position++; *p ++ = position++; } *dst ++ = 0x30AD; // KATAKANA LETTER KI *dst ++ = currentChar; previousChar = *src ++; nCount --; continue; } } if (useOffset) *p ++ = position++; *dst ++ = previousChar; previousChar = currentChar; } if (nCount == 0) { if (useOffset) *p = position; *dst ++ = previousChar; } *dst = (sal_Unicode) 0; newStr->length = sal_Int32(dst - newStr->buffer); if (useOffset) offset.realloc(newStr->length); return OUString( newStr ); // defined in rtl/usrting. The reference count is increased from 0 to 1. } } } } } <|endoftext|>
<commit_before>/* * 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. */ #define BOOST_TEST_MODULE EnumTest #include <boost/test/unit_test.hpp> #include "thrift/test/gen-cpp/EnumTest_types.h" BOOST_AUTO_TEST_SUITE( EnumTest ) BOOST_AUTO_TEST_CASE( test_enum ) { // Check that all the enum values match what we expect BOOST_CHECK_EQUAL(ME1_0, 0); BOOST_CHECK_EQUAL(ME1_1, 1); BOOST_CHECK_EQUAL(ME1_2, 2); BOOST_CHECK_EQUAL(ME1_3, 3); BOOST_CHECK_EQUAL(ME1_5, 5); BOOST_CHECK_EQUAL(ME1_6, 6); BOOST_CHECK_EQUAL(ME2_0, 0); BOOST_CHECK_EQUAL(ME2_1, 1); BOOST_CHECK_EQUAL(ME2_2, 2); BOOST_CHECK_EQUAL(ME3_0, 0); BOOST_CHECK_EQUAL(ME3_1, 1); BOOST_CHECK_EQUAL(ME3_N2, -2); BOOST_CHECK_EQUAL(ME3_N1, -1); BOOST_CHECK_EQUAL(ME3_D0, 0); BOOST_CHECK_EQUAL(ME3_D1, 1); BOOST_CHECK_EQUAL(ME3_9, 9); BOOST_CHECK_EQUAL(ME3_10, 10); BOOST_CHECK_EQUAL(ME4_A, 0x7ffffffd); BOOST_CHECK_EQUAL(ME4_B, 0x7ffffffe); BOOST_CHECK_EQUAL(ME4_C, 0x7fffffff); } BOOST_AUTO_TEST_CASE( test_enum_constant ) { MyStruct ms; BOOST_CHECK_EQUAL(ms.me2_2, 2); BOOST_CHECK_EQUAL(ms.me3_n2, -2); BOOST_CHECK_EQUAL(ms.me3_d1, 1); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>FIX: wrong include path<commit_after>/* * 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. */ #define BOOST_TEST_MODULE EnumTest #include <boost/test/unit_test.hpp> #include "gen-cpp/EnumTest_types.h" BOOST_AUTO_TEST_SUITE( EnumTest ) BOOST_AUTO_TEST_CASE( test_enum ) { // Check that all the enum values match what we expect BOOST_CHECK_EQUAL(ME1_0, 0); BOOST_CHECK_EQUAL(ME1_1, 1); BOOST_CHECK_EQUAL(ME1_2, 2); BOOST_CHECK_EQUAL(ME1_3, 3); BOOST_CHECK_EQUAL(ME1_5, 5); BOOST_CHECK_EQUAL(ME1_6, 6); BOOST_CHECK_EQUAL(ME2_0, 0); BOOST_CHECK_EQUAL(ME2_1, 1); BOOST_CHECK_EQUAL(ME2_2, 2); BOOST_CHECK_EQUAL(ME3_0, 0); BOOST_CHECK_EQUAL(ME3_1, 1); BOOST_CHECK_EQUAL(ME3_N2, -2); BOOST_CHECK_EQUAL(ME3_N1, -1); BOOST_CHECK_EQUAL(ME3_D0, 0); BOOST_CHECK_EQUAL(ME3_D1, 1); BOOST_CHECK_EQUAL(ME3_9, 9); BOOST_CHECK_EQUAL(ME3_10, 10); BOOST_CHECK_EQUAL(ME4_A, 0x7ffffffd); BOOST_CHECK_EQUAL(ME4_B, 0x7ffffffe); BOOST_CHECK_EQUAL(ME4_C, 0x7fffffff); } BOOST_AUTO_TEST_CASE( test_enum_constant ) { MyStruct ms; BOOST_CHECK_EQUAL(ms.me2_2, 2); BOOST_CHECK_EQUAL(ms.me3_n2, -2); BOOST_CHECK_EQUAL(ms.me3_d1, 1); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>// Copyright (c) 2021 by Apex.AI Inc. 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. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_UTILS_POSIX_WRAPPER_POSIX_CALL_HPP #define IOX_UTILS_POSIX_WRAPPER_POSIX_CALL_HPP #include "iceoryx_utils/cxx/attributes.hpp" #include "iceoryx_utils/cxx/expected.hpp" #include "iceoryx_utils/cxx/string.hpp" #include <cstdint> #include <cstring> namespace iox { namespace posix { static constexpr uint32_t POSIX_CALL_ERROR_STRING_SIZE = 128U; static constexpr uint64_t POSIX_CALL_EINTR_REPETITIONS = 5U; static constexpr int32_t POSIX_CALL_INVALID_ERRNO = -1; template <typename ReturnType, typename... FunctionArguments> class PosixCallBuilder; /// @brief result of a posix call template <typename T> struct PosixCallResult { static constexpr PosixCallResult INVALID_STATE{}; PosixCallResult() noexcept = default; /// @brief returns the result of std::strerror(errnum) which acquires a /// human readable error string cxx::string<POSIX_CALL_ERROR_STRING_SIZE> getHumanReadableErrnum() const noexcept; /// @brief the return value of the posix function call T value; /// @brief the errno value which was set by the posix function call int32_t errnum = POSIX_CALL_INVALID_ERRNO; }; namespace internal { template <typename ReturnType, typename... FunctionArguments> PosixCallBuilder<ReturnType, FunctionArguments...> createPosixCallBuilder(ReturnType (*posixCall)(FunctionArguments...), const char* posixFunctionName, const char* file, const int32_t line, const char* callingFunction) noexcept; template <typename ReturnType> struct PosixCallDetails { const char* posixFunctionName = nullptr; const char* file = nullptr; int32_t line = 0; const char* callingFunction = nullptr; bool hasSuccess = true; PosixCallResult<ReturnType> result; }; } // namespace internal /// @brief Calling a posix function with automated error handling. If the posix function returns /// void you do not need to use posixCall since it cannot fail, (see: man errno). /// We use a builder pattern to create a design which sets the usage contract so that it /// cannot be used in the wrong way. /// @code /// iox::posix::posixCall(sem_timedwait)(handle, timeout) /// .successReturnValue(0) /// .evaluateWithIgnoredErrnos(ETIMEDOUT) // can be a comma separated list of errnos /// .and_then([](auto & result){ /// std::cout << result.value << std::endl; // return value of sem_timedwait /// std::cout << result.errno << std::endl; // errno which was set by sem_timedwait /// std::cout << result.getHumanReadableErrnum() << std::endl; // get string returned by strerror(errno) /// }) /// .or_else([](auto & result){ /// std::cout << result.value << std::endl; // return value of sem_timedwait /// std::cout << result.errno << std::endl; // errno which was set by sem_timedwait /// std::cout << result.getHumanReadableErrnum() << std::endl; // get string returned by strerror(errno) /// }) /// /// // when your posix call signals failure with one specific return value use /// // .failureReturnValue(_) instead of .successReturnValue(_) /// /// // if you do not want to ignore errnos use /// // .evaluate() instead of .evaluateWithIgnoredErrnos(_) /// @endcode #define posixCall(f) internal::createPosixCallBuilder(f, #f, __FILE__, __LINE__, __PRETTY_FUNCTION__) /// @brief class which is created by the verificator to evaluate the result of a posix call template <typename ReturnType> class IOX_NO_DISCARD PosixCallEvaluator { public: /// @brief evaluate the result of a posix call and ignore specified errnos /// @tparam IgnoredErrnos a list of int32_t variables /// @param[in] ignoredErrnos the int32_t values of the errnos which should be ignored /// @return returns an expected which contains in both cases a PosixCallResult<ReturnType> with the return value /// (.value) and the errno value (.errnum) of the function call template <typename... IgnoredErrnos> cxx::expected<PosixCallResult<ReturnType>, PosixCallResult<ReturnType>> evaluateWithIgnoredErrnos(const IgnoredErrnos... ignoredErrnos) const&& noexcept; /// @brief evaluate the result of a posix call /// @return returns an expected which contains in both cases a PosixCallResult<ReturnType> with the return value /// (.value) and the errno value (.errnum) of the function call cxx::expected<PosixCallResult<ReturnType>, PosixCallResult<ReturnType>> evaluate() const&& noexcept; private: template <typename> friend class PosixCallVerificator; explicit PosixCallEvaluator(internal::PosixCallDetails<ReturnType>& details) noexcept; private: internal::PosixCallDetails<ReturnType>& m_details; }; /// @brief class which verifies the return value of a posix function call template <typename ReturnType> class IOX_NO_DISCARD PosixCallVerificator { public: /// @brief the posix function call defines success through a single value /// @param[in] value the value which defines success /// @return the PosixCallEvaluator which evaluates the errno values PosixCallEvaluator<ReturnType> successReturnValue(const ReturnType value) && noexcept; /// @brief the posix function call defines failure through a single value /// @param[in] value the value which defines failure /// @return the PosixCallEvaluator which evaluates the errno values PosixCallEvaluator<ReturnType> failureReturnValue(const ReturnType value) && noexcept; private: template <typename, typename...> friend class PosixCallBuilder; explicit PosixCallVerificator(internal::PosixCallDetails<ReturnType>& details) noexcept; private: internal::PosixCallDetails<ReturnType>& m_details; }; template <typename ReturnType, typename... FunctionArguments> class IOX_NO_DISCARD PosixCallBuilder { public: /// @brief input function type using FunctionType_t = ReturnType (*)(FunctionArguments...); /// @brief Call the underlying function with the provided arguments. If the underlying function fails and sets the /// errno to EINTR the call is repeated at most POSIX_CALL_EINTR_REPETITIONS times /// @param[in] arguments arguments which will be provided to the posix function /// @return the PosixCallVerificator to verify the return value PosixCallVerificator<ReturnType> operator()(FunctionArguments... arguments) && noexcept; private: template <typename ReturnType_, typename... FunctionArguments_> friend PosixCallBuilder<ReturnType_, FunctionArguments_...> internal::createPosixCallBuilder(ReturnType_ (*posixCall)(FunctionArguments_...), const char* posixFunctionName, const char* file, const int32_t line, const char* callingFunction) noexcept; PosixCallBuilder(FunctionType_t posixCall, const char* posixFunctionName, const char* file, const int32_t line, const char* callingFunction) noexcept; private: FunctionType_t m_posixCall = nullptr; internal::PosixCallDetails<ReturnType> m_details; }; } // namespace posix } // namespace iox #include "iceoryx_utils/internal/posix_wrapper/posix_call.inl" #endif <commit_msg>iox-#418 INVALID_STATE compile time constant not supported on mac os<commit_after>// Copyright (c) 2021 by Apex.AI Inc. 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. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_UTILS_POSIX_WRAPPER_POSIX_CALL_HPP #define IOX_UTILS_POSIX_WRAPPER_POSIX_CALL_HPP #include "iceoryx_utils/cxx/attributes.hpp" #include "iceoryx_utils/cxx/expected.hpp" #include "iceoryx_utils/cxx/string.hpp" #include <cstdint> #include <cstring> namespace iox { namespace posix { static constexpr uint32_t POSIX_CALL_ERROR_STRING_SIZE = 128U; static constexpr uint64_t POSIX_CALL_EINTR_REPETITIONS = 5U; static constexpr int32_t POSIX_CALL_INVALID_ERRNO = -1; template <typename ReturnType, typename... FunctionArguments> class PosixCallBuilder; /// @brief result of a posix call template <typename T> struct PosixCallResult { static const PosixCallResult INVALID_STATE; PosixCallResult() noexcept = default; /// @brief returns the result of std::strerror(errnum) which acquires a /// human readable error string cxx::string<POSIX_CALL_ERROR_STRING_SIZE> getHumanReadableErrnum() const noexcept; /// @brief the return value of the posix function call T value; /// @brief the errno value which was set by the posix function call int32_t errnum = POSIX_CALL_INVALID_ERRNO; }; template <typename T> PosixCallResult<T> const PosixCallResult<T>::INVALID_STATE{{}, POSIX_CALL_INVALID_ERRNO}; namespace internal { template <typename ReturnType, typename... FunctionArguments> PosixCallBuilder<ReturnType, FunctionArguments...> createPosixCallBuilder(ReturnType (*posixCall)(FunctionArguments...), const char* posixFunctionName, const char* file, const int32_t line, const char* callingFunction) noexcept; template <typename ReturnType> struct PosixCallDetails { const char* posixFunctionName = nullptr; const char* file = nullptr; int32_t line = 0; const char* callingFunction = nullptr; bool hasSuccess = true; PosixCallResult<ReturnType> result; }; } // namespace internal /// @brief Calling a posix function with automated error handling. If the posix function returns /// void you do not need to use posixCall since it cannot fail, (see: man errno). /// We use a builder pattern to create a design which sets the usage contract so that it /// cannot be used in the wrong way. /// @code /// iox::posix::posixCall(sem_timedwait)(handle, timeout) /// .successReturnValue(0) /// .evaluateWithIgnoredErrnos(ETIMEDOUT) // can be a comma separated list of errnos /// .and_then([](auto & result){ /// std::cout << result.value << std::endl; // return value of sem_timedwait /// std::cout << result.errno << std::endl; // errno which was set by sem_timedwait /// std::cout << result.getHumanReadableErrnum() << std::endl; // get string returned by strerror(errno) /// }) /// .or_else([](auto & result){ /// std::cout << result.value << std::endl; // return value of sem_timedwait /// std::cout << result.errno << std::endl; // errno which was set by sem_timedwait /// std::cout << result.getHumanReadableErrnum() << std::endl; // get string returned by strerror(errno) /// }) /// /// // when your posix call signals failure with one specific return value use /// // .failureReturnValue(_) instead of .successReturnValue(_) /// /// // if you do not want to ignore errnos use /// // .evaluate() instead of .evaluateWithIgnoredErrnos(_) /// @endcode #define posixCall(f) internal::createPosixCallBuilder(f, #f, __FILE__, __LINE__, __PRETTY_FUNCTION__) /// @brief class which is created by the verificator to evaluate the result of a posix call template <typename ReturnType> class IOX_NO_DISCARD PosixCallEvaluator { public: /// @brief evaluate the result of a posix call and ignore specified errnos /// @tparam IgnoredErrnos a list of int32_t variables /// @param[in] ignoredErrnos the int32_t values of the errnos which should be ignored /// @return returns an expected which contains in both cases a PosixCallResult<ReturnType> with the return value /// (.value) and the errno value (.errnum) of the function call template <typename... IgnoredErrnos> cxx::expected<PosixCallResult<ReturnType>, PosixCallResult<ReturnType>> evaluateWithIgnoredErrnos(const IgnoredErrnos... ignoredErrnos) const&& noexcept; /// @brief evaluate the result of a posix call /// @return returns an expected which contains in both cases a PosixCallResult<ReturnType> with the return value /// (.value) and the errno value (.errnum) of the function call cxx::expected<PosixCallResult<ReturnType>, PosixCallResult<ReturnType>> evaluate() const&& noexcept; private: template <typename> friend class PosixCallVerificator; explicit PosixCallEvaluator(internal::PosixCallDetails<ReturnType>& details) noexcept; private: internal::PosixCallDetails<ReturnType>& m_details; }; /// @brief class which verifies the return value of a posix function call template <typename ReturnType> class IOX_NO_DISCARD PosixCallVerificator { public: /// @brief the posix function call defines success through a single value /// @param[in] value the value which defines success /// @return the PosixCallEvaluator which evaluates the errno values PosixCallEvaluator<ReturnType> successReturnValue(const ReturnType value) && noexcept; /// @brief the posix function call defines failure through a single value /// @param[in] value the value which defines failure /// @return the PosixCallEvaluator which evaluates the errno values PosixCallEvaluator<ReturnType> failureReturnValue(const ReturnType value) && noexcept; private: template <typename, typename...> friend class PosixCallBuilder; explicit PosixCallVerificator(internal::PosixCallDetails<ReturnType>& details) noexcept; private: internal::PosixCallDetails<ReturnType>& m_details; }; template <typename ReturnType, typename... FunctionArguments> class IOX_NO_DISCARD PosixCallBuilder { public: /// @brief input function type using FunctionType_t = ReturnType (*)(FunctionArguments...); /// @brief Call the underlying function with the provided arguments. If the underlying function fails and sets the /// errno to EINTR the call is repeated at most POSIX_CALL_EINTR_REPETITIONS times /// @param[in] arguments arguments which will be provided to the posix function /// @return the PosixCallVerificator to verify the return value PosixCallVerificator<ReturnType> operator()(FunctionArguments... arguments) && noexcept; private: template <typename ReturnType_, typename... FunctionArguments_> friend PosixCallBuilder<ReturnType_, FunctionArguments_...> internal::createPosixCallBuilder(ReturnType_ (*posixCall)(FunctionArguments_...), const char* posixFunctionName, const char* file, const int32_t line, const char* callingFunction) noexcept; PosixCallBuilder(FunctionType_t posixCall, const char* posixFunctionName, const char* file, const int32_t line, const char* callingFunction) noexcept; private: FunctionType_t m_posixCall = nullptr; internal::PosixCallDetails<ReturnType> m_details; }; } // namespace posix } // namespace iox #include "iceoryx_utils/internal/posix_wrapper/posix_call.inl" #endif <|endoftext|>
<commit_before>/************************************************************************ filename: FalProgressBar.cpp created: Sat Jul 2 2005 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /************************************************************************* Crazy Eddie's GUI System (http://www.cegui.org.uk) Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *************************************************************************/ #include "FalProgressBar.h" #include "falagard/CEGUIFalWidgetLookManager.h" #include "falagard/CEGUIFalWidgetLookFeel.h" #include "elements/CEGUIProgressBar.h" // Start of CEGUI namespace section namespace CEGUI { const utf8 FalagardProgressBar::TypeName[] = "Falagard/ProgressBar"; FalagardProgressBarProperties::VerticalProgress FalagardProgressBar::d_verticalProperty; FalagardProgressBarProperties::ReversedProgress FalagardProgressBar::d_reversedProperty; FalagardProgressBar::FalagardProgressBar(const String& type) : WindowRenderer(type, "ProgressBar"), d_vertical(false), d_reversed(false) { registerProperty(&d_verticalProperty); registerProperty(&d_reversedProperty); } void FalagardProgressBar::render() { const StateImagery* imagery; // get WidgetLookFeel for the assigned look. const WidgetLookFeel& wlf = getLookNFeel(); // try and get imagery for our current state imagery = &wlf.getStateImagery(d_window->isDisabled() ? "Disabled" : "Enabled"); // peform the rendering operation. imagery->render(*d_window); // get imagery for actual progress rendering imagery = &wlf.getStateImagery(d_window->isDisabled() ? "DisabledProgress" : "EnabledProgress"); // get target rect for this imagery Rect progressRect(wlf.getNamedArea("ProgressArea").getArea().getPixelRect(*d_window)); // calculate a clipper according to the current progress. Rect progressClipper(progressRect); ProgressBar* w = (ProgressBar*)d_window; if (d_vertical) { float height = progressRect.getHeight() * w->getProgress(); if (d_reversed) { progressRect.setHeight(height); } else { progressClipper.d_top = progressClipper.d_bottom - height; } } else { float width = progressRect.getWidth() * w->getProgress(); if (d_reversed) { progressClipper.d_left = progressClipper.d_right - width; } else { progressRect.setWidth(width); } } // peform the rendering operation. imagery->render(*d_window, progressRect, 0, &progressClipper); } bool FalagardProgressBar::isVertical() const { return d_vertical; } bool FalagardProgressBar::isReversed() const { return d_reversed; } void FalagardProgressBar::setVertical(bool setting) { d_vertical = setting; } void FalagardProgressBar::setReversed(bool setting) { d_reversed = setting; } } // End of CEGUI namespace section <commit_msg>Fixed progressbar WR.<commit_after>/************************************************************************ filename: FalProgressBar.cpp created: Sat Jul 2 2005 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /************************************************************************* Crazy Eddie's GUI System (http://www.cegui.org.uk) Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *************************************************************************/ #include "FalProgressBar.h" #include "falagard/CEGUIFalWidgetLookManager.h" #include "falagard/CEGUIFalWidgetLookFeel.h" #include "elements/CEGUIProgressBar.h" // Start of CEGUI namespace section namespace CEGUI { const utf8 FalagardProgressBar::TypeName[] = "Falagard/ProgressBar"; FalagardProgressBarProperties::VerticalProgress FalagardProgressBar::d_verticalProperty; FalagardProgressBarProperties::ReversedProgress FalagardProgressBar::d_reversedProperty; FalagardProgressBar::FalagardProgressBar(const String& type) : WindowRenderer(type, "ProgressBar"), d_vertical(false), d_reversed(false) { registerProperty(&d_verticalProperty); registerProperty(&d_reversedProperty); } void FalagardProgressBar::render() { const StateImagery* imagery; // get WidgetLookFeel for the assigned look. const WidgetLookFeel& wlf = getLookNFeel(); // try and get imagery for our current state imagery = &wlf.getStateImagery(d_window->isDisabled() ? "Disabled" : "Enabled"); // peform the rendering operation. imagery->render(*d_window); // get imagery for actual progress rendering imagery = &wlf.getStateImagery(d_window->isDisabled() ? "DisabledProgress" : "EnabledProgress"); // get target rect for this imagery Rect progressRect(wlf.getNamedArea("ProgressArea").getArea().getPixelRect(*d_window)); // calculate a clipper according to the current progress. Rect progressClipper(progressRect); ProgressBar* w = (ProgressBar*)d_window; if (d_vertical) { float height = progressRect.getHeight() * w->getProgress(); if (d_reversed) { progressRect.setHeight(height); } else { progressRect.d_top = progressRect.d_bottom - height; } } else { float width = progressRect.getWidth() * w->getProgress(); if (d_reversed) { progressRect.d_left = progressRect.d_right - width; } else { progressRect.setWidth(width); } } // peform the rendering operation. imagery->render(*d_window, progressRect, 0, &progressClipper); } bool FalagardProgressBar::isVertical() const { return d_vertical; } bool FalagardProgressBar::isReversed() const { return d_reversed; } void FalagardProgressBar::setVertical(bool setting) { d_vertical = setting; } void FalagardProgressBar::setReversed(bool setting) { d_reversed = setting; } } // End of CEGUI namespace section <|endoftext|>
<commit_before>/* * Copyright (C) 2004-2008 Marc Boris Duerner * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cxxtools/streambuffer.h" #include <algorithm> #include <stdexcept> #include <cstring> #include <cxxtools/log.h> log_define("cxxtools.streambuffer") namespace cxxtools { StreamBuffer::StreamBuffer(IODevice& ioDevice, size_t bufferSize, bool extend) : _ioDevice(&ioDevice), _ibufferSize(bufferSize+4), _ibuffer(0), _obufferSize(bufferSize), _obuffer(0), _oextend(extend), _pbmax(4), _reading(false), _flushing(false) { this->setg(0, 0, 0); this->setp(0, 0); this->attach(ioDevice); } StreamBuffer::StreamBuffer(size_t bufferSize, bool extend) : _ioDevice(0), _ibufferSize(bufferSize+4), _ibuffer(0), _obufferSize(bufferSize), _obuffer(0), _oextend(extend), _pbmax(4), _reading(false), _flushing(false) { this->setg(0, 0, 0); this->setp(0, 0); } StreamBuffer::~StreamBuffer() { delete[] _ibuffer; delete[] _obuffer; } void StreamBuffer::attach(IODevice& ioDevice) { if( ioDevice.busy() ) throw IOPending( CXXTOOLS_ERROR_MSG("IODevice in use") ); if(_ioDevice) { if( _ioDevice->busy() ) throw IOPending( CXXTOOLS_ERROR_MSG("IODevice in use") ); disconnect(ioDevice.inputReady, *this, &StreamBuffer::onRead); disconnect(ioDevice.outputReady, *this, &StreamBuffer::onWrite); } _ioDevice = &ioDevice; connect(ioDevice.inputReady, *this, &StreamBuffer::onRead); connect(ioDevice.outputReady, *this, &StreamBuffer::onWrite); } IODevice* StreamBuffer::device() { return _ioDevice; } void StreamBuffer::beginRead() { if(_reading || _ioDevice == 0) return; if( ! _ibuffer ) { _ibuffer = new char[_ibufferSize]; } size_t putback = _pbmax; size_t leftover = 0; // keep chars for putback if( this->gptr() ) { putback = std::min<size_t>( gptr() - eback(), _pbmax); char* to = _ibuffer + _pbmax - putback; char* from = this->gptr() - putback; if(to == from) throw std::logic_error( CXXTOOLS_ERROR_MSG("StreamBuffer is full") ); leftover = egptr() - gptr(); std::memmove( to, from, putback + leftover ); } size_t used = _pbmax + leftover; _ioDevice->beginRead( _ibuffer + used, _ibufferSize - used ); _reading = true; this->setg( _ibuffer + (_pbmax - putback), // start of get area _ibuffer + used, // gptr position _ibuffer + used ); // end of get area } void StreamBuffer::onRead(IODevice& dev) { this->endRead(); inputReady.send(*this); } void StreamBuffer::endRead() { size_t readSize = _ioDevice->endRead(); _reading = false; this->setg( this->eback(), // start of get area this->gptr(), // gptr position this->egptr() + readSize ); // end of get area } StreamBuffer::int_type StreamBuffer::underflow() { log_trace("underflow"); if( ! _ioDevice ) return traits_type::eof(); if(_reading) this->endRead(); if( this->gptr() < this->egptr() ) return traits_type::to_int_type( *(this->gptr()) ); if( _ioDevice->eof() ) return traits_type::eof(); if( ! _ibuffer ) { _ibuffer = new char[_ibufferSize]; } size_t putback = _pbmax; if( this->gptr() ) { putback = std::min<size_t>(this->gptr() - this->eback(), _pbmax); std::memmove( _ibuffer + (_pbmax - putback), this->gptr() - putback, putback ); } size_t readSize = _ioDevice->read( _ibuffer + _pbmax, _ibufferSize - _pbmax ); this->setg( _ibuffer + _pbmax - putback, // start of get area _ibuffer + _pbmax, // gptr position _ibuffer + _pbmax + readSize ); // end of get area if( _ioDevice->eof() ) return traits_type::eof(); return traits_type::to_int_type( *(this->gptr()) ); } std::streamsize StreamBuffer::showfull() { return 0; } void StreamBuffer::beginWrite() { log_trace("beginWrite; out_avail=" << out_avail()); if(_flushing || _ioDevice == 0 ) return; if( this->pptr() ) { size_t avail = this->pptr() - this->pbase(); if(avail > 0) { _ioDevice->beginWrite(_obuffer, avail); _flushing = true; } } } void StreamBuffer::discard() { if (_reading || _flushing) throw IOPending( CXXTOOLS_ERROR_MSG("discard failed - streambuffer is in use") ); if (gptr()) this->setg(_ibuffer, _ibuffer + _ibufferSize, _ibuffer + _ibufferSize); if (pptr()) this->setp(_obuffer, _obuffer + _obufferSize); } void StreamBuffer::onWrite(IODevice& dev) { log_trace("onWrite"); this->endWrite(); outputReady.send(*this); } void StreamBuffer::endWrite() { log_trace("endWrite; out_avail=" << out_avail()); _flushing = false; size_t leftover = 0; if( this->pptr() ) { size_t avail = this->pptr() - this->pbase(); size_t written = _ioDevice->endWrite(); leftover = avail - written; if(leftover > 0) { traits_type::move(_obuffer, _obuffer + written, leftover); } } this->setp(_obuffer, _obuffer + _obufferSize); this->pbump( leftover ); } StreamBuffer::int_type StreamBuffer::overflow(int_type ch) { log_trace("overflow(" << ch << ')'); if( ! _ioDevice ) return traits_type::eof(); if( ! _obuffer ) { _obuffer = new char[_obufferSize]; this->setp(_obuffer, _obuffer + _obufferSize); } else if(_flushing) // beginWrite is unfinished { this->endWrite(); } else if (traits_type::eq_int_type( ch, traits_type::eof() ) || !_oextend) { // normal blocking overflow case size_t avail = this->pptr() - _obuffer; size_t written = _ioDevice->write(_obuffer, avail); size_t leftover = avail - written; if(leftover > 0) { traits_type::move(_obuffer, _obuffer + written, leftover); } this->setp(_obuffer, _obuffer + _obufferSize); this->pbump( leftover ); } else { // if the buffer area is extensible and overflow is not called by // sync/flush we copy the output buffer to a larger one size_t bufsize = _obufferSize + (_obufferSize/2); char* buf = new char[ bufsize ]; traits_type::move(buf, _obuffer, _obufferSize); std::swap(_obuffer, buf); _obufferSize = bufsize; delete [] buf; } // if the overflow char is not EOF put it in buffer if( traits_type::eq_int_type(ch, traits_type::eof()) == false ) { *this->pptr() = traits_type::to_char_type(ch); this->pbump(1); } return traits_type::not_eof(ch); } StreamBuffer::int_type StreamBuffer::pbackfail(StreamBuffer::int_type) { return traits_type::eof(); } int StreamBuffer::sync() { log_trace("sync"); if( ! _ioDevice ) return 0; if( pptr() ) { while( this->pptr() > this->pbase() ) { const int_type ch = this->overflow( traits_type::eof() ); if( ch == traits_type::eof() ) { return -1; } _ioDevice->sync(); } } return 0; } std::streamsize StreamBuffer::xspeekn(char* buffer, std::streamsize size) { if( traits_type::eof() == this->underflow() ) return 0; const std::streamsize avail = this->egptr() - this->gptr(); size = std::min(avail, size); if(size == 0) { return 0; } std::memcpy(buffer, this->gptr(), sizeof(char) * size); return size; } StreamBuffer::pos_type StreamBuffer::seekoff(off_type off, std::ios::seekdir dir, std::ios::openmode) { pos_type ret = pos_type( off_type(-1) ); if ( ! _ioDevice || ! _ioDevice->enabled() || ! _ioDevice->seekable() || off == 0) { return ret; } if(_flushing) { this->endWrite(); } if(_reading) { this->endRead(); } ret = _ioDevice->seek(off, dir); // eliminate currently buffered sequence discard(); return ret; } StreamBuffer::pos_type StreamBuffer::seekpos(pos_type p, std::ios::openmode mode) { return this->seekoff(p, std::ios::beg, mode); } } <commit_msg>fix streambuffer extend<commit_after>/* * Copyright (C) 2004-2008 Marc Boris Duerner * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cxxtools/streambuffer.h" #include <algorithm> #include <stdexcept> #include <cstring> #include <cxxtools/log.h> log_define("cxxtools.streambuffer") namespace cxxtools { StreamBuffer::StreamBuffer(IODevice& ioDevice, size_t bufferSize, bool extend) : _ioDevice(&ioDevice), _ibufferSize(bufferSize+4), _ibuffer(0), _obufferSize(bufferSize), _obuffer(0), _oextend(extend), _pbmax(4), _reading(false), _flushing(false) { this->setg(0, 0, 0); this->setp(0, 0); this->attach(ioDevice); } StreamBuffer::StreamBuffer(size_t bufferSize, bool extend) : _ioDevice(0), _ibufferSize(bufferSize+4), _ibuffer(0), _obufferSize(bufferSize), _obuffer(0), _oextend(extend), _pbmax(4), _reading(false), _flushing(false) { this->setg(0, 0, 0); this->setp(0, 0); } StreamBuffer::~StreamBuffer() { delete[] _ibuffer; delete[] _obuffer; } void StreamBuffer::attach(IODevice& ioDevice) { if( ioDevice.busy() ) throw IOPending( CXXTOOLS_ERROR_MSG("IODevice in use") ); if(_ioDevice) { if( _ioDevice->busy() ) throw IOPending( CXXTOOLS_ERROR_MSG("IODevice in use") ); disconnect(ioDevice.inputReady, *this, &StreamBuffer::onRead); disconnect(ioDevice.outputReady, *this, &StreamBuffer::onWrite); } _ioDevice = &ioDevice; connect(ioDevice.inputReady, *this, &StreamBuffer::onRead); connect(ioDevice.outputReady, *this, &StreamBuffer::onWrite); } IODevice* StreamBuffer::device() { return _ioDevice; } void StreamBuffer::beginRead() { if(_reading || _ioDevice == 0) return; if( ! _ibuffer ) { _ibuffer = new char[_ibufferSize]; } size_t putback = _pbmax; size_t leftover = 0; // keep chars for putback if( this->gptr() ) { putback = std::min<size_t>( gptr() - eback(), _pbmax); char* to = _ibuffer + _pbmax - putback; char* from = this->gptr() - putback; if(to == from) throw std::logic_error( CXXTOOLS_ERROR_MSG("StreamBuffer is full") ); leftover = egptr() - gptr(); std::memmove( to, from, putback + leftover ); } size_t used = _pbmax + leftover; _ioDevice->beginRead( _ibuffer + used, _ibufferSize - used ); _reading = true; this->setg( _ibuffer + (_pbmax - putback), // start of get area _ibuffer + used, // gptr position _ibuffer + used ); // end of get area } void StreamBuffer::onRead(IODevice& dev) { this->endRead(); inputReady.send(*this); } void StreamBuffer::endRead() { size_t readSize = _ioDevice->endRead(); _reading = false; this->setg( this->eback(), // start of get area this->gptr(), // gptr position this->egptr() + readSize ); // end of get area } StreamBuffer::int_type StreamBuffer::underflow() { log_trace("underflow"); if( ! _ioDevice ) return traits_type::eof(); if(_reading) this->endRead(); if( this->gptr() < this->egptr() ) return traits_type::to_int_type( *(this->gptr()) ); if( _ioDevice->eof() ) return traits_type::eof(); if( ! _ibuffer ) { _ibuffer = new char[_ibufferSize]; } size_t putback = _pbmax; if( this->gptr() ) { putback = std::min<size_t>(this->gptr() - this->eback(), _pbmax); std::memmove( _ibuffer + (_pbmax - putback), this->gptr() - putback, putback ); } size_t readSize = _ioDevice->read( _ibuffer + _pbmax, _ibufferSize - _pbmax ); this->setg( _ibuffer + _pbmax - putback, // start of get area _ibuffer + _pbmax, // gptr position _ibuffer + _pbmax + readSize ); // end of get area if( _ioDevice->eof() ) return traits_type::eof(); return traits_type::to_int_type( *(this->gptr()) ); } std::streamsize StreamBuffer::showfull() { return 0; } void StreamBuffer::beginWrite() { log_trace("beginWrite; out_avail=" << out_avail()); if(_flushing || _ioDevice == 0 ) return; if( this->pptr() ) { size_t avail = this->pptr() - this->pbase(); if(avail > 0) { _ioDevice->beginWrite(_obuffer, avail); _flushing = true; } } } void StreamBuffer::discard() { if (_reading || _flushing) throw IOPending( CXXTOOLS_ERROR_MSG("discard failed - streambuffer is in use") ); if (gptr()) this->setg(_ibuffer, _ibuffer + _ibufferSize, _ibuffer + _ibufferSize); if (pptr()) this->setp(_obuffer, _obuffer + _obufferSize); } void StreamBuffer::onWrite(IODevice& dev) { log_trace("onWrite"); this->endWrite(); outputReady.send(*this); } void StreamBuffer::endWrite() { log_trace("endWrite; out_avail=" << out_avail()); _flushing = false; size_t leftover = 0; if( this->pptr() ) { size_t avail = this->pptr() - this->pbase(); size_t written = _ioDevice->endWrite(); leftover = avail - written; if(leftover > 0) { traits_type::move(_obuffer, _obuffer + written, leftover); } } this->setp(_obuffer, _obuffer + _obufferSize); this->pbump( leftover ); } StreamBuffer::int_type StreamBuffer::overflow(int_type ch) { log_trace("overflow(" << ch << ')'); if( ! _ioDevice ) return traits_type::eof(); if( ! _obuffer ) { _obuffer = new char[_obufferSize]; this->setp(_obuffer, _obuffer + _obufferSize); } else if(_flushing) // beginWrite is unfinished { this->endWrite(); } else if (traits_type::eq_int_type( ch, traits_type::eof() ) || !_oextend) { // normal blocking overflow case size_t avail = this->pptr() - _obuffer; size_t written = _ioDevice->write(_obuffer, avail); size_t leftover = avail - written; if(leftover > 0) { traits_type::move(_obuffer, _obuffer + written, leftover); } this->setp(_obuffer, _obuffer + _obufferSize); this->pbump( leftover ); } else { // if the buffer area is extensible and overflow is not called by // sync/flush we copy the output buffer to a larger one size_t bufsize = _obufferSize + (_obufferSize/2); char* buf = new char[ bufsize ]; traits_type::copy(buf, _obuffer, _obufferSize); std::swap(_obuffer, buf); this->setp(_obuffer, _obuffer + bufsize); this->pbump( _obufferSize ); _obufferSize = bufsize; delete [] buf; } // if the overflow char is not EOF put it in buffer if( traits_type::eq_int_type(ch, traits_type::eof()) == false ) { *this->pptr() = traits_type::to_char_type(ch); this->pbump(1); } return traits_type::not_eof(ch); } StreamBuffer::int_type StreamBuffer::pbackfail(StreamBuffer::int_type) { return traits_type::eof(); } int StreamBuffer::sync() { log_trace("sync"); if( ! _ioDevice ) return 0; if( pptr() ) { while( this->pptr() > this->pbase() ) { const int_type ch = this->overflow( traits_type::eof() ); if( ch == traits_type::eof() ) { return -1; } _ioDevice->sync(); } } return 0; } std::streamsize StreamBuffer::xspeekn(char* buffer, std::streamsize size) { if( traits_type::eof() == this->underflow() ) return 0; const std::streamsize avail = this->egptr() - this->gptr(); size = std::min(avail, size); if(size == 0) { return 0; } std::memcpy(buffer, this->gptr(), sizeof(char) * size); return size; } StreamBuffer::pos_type StreamBuffer::seekoff(off_type off, std::ios::seekdir dir, std::ios::openmode) { pos_type ret = pos_type( off_type(-1) ); if ( ! _ioDevice || ! _ioDevice->enabled() || ! _ioDevice->seekable() || off == 0) { return ret; } if(_flushing) { this->endWrite(); } if(_reading) { this->endRead(); } ret = _ioDevice->seek(off, dir); // eliminate currently buffered sequence discard(); return ret; } StreamBuffer::pos_type StreamBuffer::seekpos(pos_type p, std::ios::openmode mode) { return this->seekoff(p, std::ios::beg, mode); } } <|endoftext|>
<commit_before>// Copyright (c) 2013-2014 The Bitcoin Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcserver.h" #include "rpcclient.h" #include "base58.h" #include "wallet.h" #include <boost/algorithm/string.hpp> #include <boost/test/unit_test.hpp> using namespace std; using namespace json_spirit; extern Array createArgs(int nRequired, const char* address1=NULL, const char* address2=NULL); extern Value CallRPC(string args); extern CWallet* pwalletMain; BOOST_AUTO_TEST_SUITE(rpc_wallet_tests) BOOST_AUTO_TEST_CASE(rpc_addmultisig) { LOCK(pwalletMain->cs_wallet); rpcfn_type addmultisig = tableRPC["addmultisigaddress"]->actor; // old, 65-byte-long: const char address1Hex[] = "0434e3e09f49ea168c5bbf53f877ff4206923858aab7c7e1df25bc263978107c95e35065a27ef6f1b27222db0ec97e0e895eaca603d3ee0d4c060ce3d8a00286c8"; // new, compressed: const char address2Hex[] = "0388c2037017c62240b6b72ac1a2a5f94da790596ebd06177c8572752922165cb4"; Value v; CBitcoinAddress address; BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex), false)); address.SetString(v.get_str()); BOOST_CHECK(address.IsValid() && address.IsScript()); BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex, address2Hex), false)); address.SetString(v.get_str()); BOOST_CHECK(address.IsValid() && address.IsScript()); BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(2, address1Hex, address2Hex), false)); address.SetString(v.get_str()); BOOST_CHECK(address.IsValid() && address.IsScript()); BOOST_CHECK_THROW(addmultisig(createArgs(0), false), runtime_error); BOOST_CHECK_THROW(addmultisig(createArgs(1), false), runtime_error); BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), runtime_error); BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), runtime_error); BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), runtime_error); string short1(address1Hex, address1Hex+sizeof(address1Hex)-2); // last byte missing BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), runtime_error); string short2(address1Hex+1, address1Hex+sizeof(address1Hex)); // first byte missing BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), runtime_error); } BOOST_AUTO_TEST_CASE(rpc_wallet) { // Test RPC calls for various wallet statistics Value r; LOCK2(cs_main, pwalletMain->cs_wallet); CPubKey demoPubkey = pwalletMain->GenerateNewKey(); CBitcoinAddress demoAddress = CBitcoinAddress(CTxDestination(demoPubkey.GetID())); Value retValue; string strAccount = "walletDemoAccount"; string strPurpose = "receive"; BOOST_CHECK_NO_THROW({ /*Initialize Wallet with an account */ CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; account.vchPubKey = demoPubkey; pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, strPurpose); walletdb.WriteAccount(strAccount, account); }); CPubKey setaccountDemoPubkey = pwalletMain->GenerateNewKey(); CBitcoinAddress setaccountDemoAddress = CBitcoinAddress(CTxDestination(setaccountDemoPubkey.GetID())); /********************************* * setaccount *********************************/ BOOST_CHECK_NO_THROW(CallRPC("setaccount " + setaccountDemoAddress.ToString() + " nullaccount")); /* 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ is not owned by the test wallet. */ BOOST_CHECK_THROW(CallRPC("setaccount 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ nullaccount"), runtime_error); BOOST_CHECK_THROW(CallRPC("setaccount"), runtime_error); /* 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X (33 chars) is an illegal address (should be 34 chars) */ BOOST_CHECK_THROW(CallRPC("setaccount 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X nullaccount"), runtime_error); /********************************* * listunspent *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listunspent")); BOOST_CHECK_THROW(CallRPC("listunspent string"), runtime_error); BOOST_CHECK_THROW(CallRPC("listunspent 0 string"), runtime_error); BOOST_CHECK_THROW(CallRPC("listunspent 0 1 not_array"), runtime_error); BOOST_CHECK_THROW(CallRPC("listunspent 0 1 [] extra"), runtime_error); BOOST_CHECK_NO_THROW(r=CallRPC("listunspent 0 1 []")); BOOST_CHECK(r.get_array().empty()); /********************************* * listreceivedbyaddress *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress")); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0")); BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress not_int"), runtime_error); BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 not_bool"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0 true")); BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 true extra"), runtime_error); /********************************* * listreceivedbyaccount *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount")); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0")); BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount not_int"), runtime_error); BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 not_bool"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0 true")); BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 true extra"), runtime_error); /********************************* * getrawchangeaddress *********************************/ BOOST_CHECK_NO_THROW(CallRPC("getrawchangeaddress")); /********************************* * getnewaddress *********************************/ BOOST_CHECK_NO_THROW(CallRPC("getnewaddress")); BOOST_CHECK_NO_THROW(CallRPC("getnewaddress getnewaddress_demoaccount")); /********************************* * getaccountaddress *********************************/ BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress \"\"")); BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress accountThatDoesntExists")); // Should generate a new account BOOST_CHECK_NO_THROW(retValue = CallRPC("getaccountaddress " + strAccount)); BOOST_CHECK(CBitcoinAddress(retValue.get_str()).Get() == demoAddress.Get()); /********************************* * getaccount *********************************/ BOOST_CHECK_THROW(CallRPC("getaccount"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("getaccount " + demoAddress.ToString())); /********************************* * signmessage + verifymessage *********************************/ BOOST_CHECK_NO_THROW(retValue = CallRPC("signmessage " + demoAddress.ToString() + " mymessage")); BOOST_CHECK_THROW(CallRPC("signmessage"), runtime_error); /* Should throw error because this address is not loaded in the wallet */ BOOST_CHECK_THROW(CallRPC("signmessage 1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ mymessage"), runtime_error); /* missing arguments */ BOOST_CHECK_THROW(CallRPC("verifymessage "+ demoAddress.ToString()), runtime_error); BOOST_CHECK_THROW(CallRPC("verifymessage "+ demoAddress.ToString() + " " + retValue.get_str()), runtime_error); /* Illegal address */ BOOST_CHECK_THROW(CallRPC("verifymessage 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X " + retValue.get_str() + " mymessage"), runtime_error); /* wrong address */ BOOST_CHECK(CallRPC("verifymessage 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ " + retValue.get_str() + " mymessage").get_bool() == false); /* Correct address and signature but wrong message */ BOOST_CHECK(CallRPC("verifymessage "+ demoAddress.ToString() + " " + retValue.get_str() + " wrongmessage").get_bool() == false); /* Correct address, message and signature*/ BOOST_CHECK(CallRPC("verifymessage "+ demoAddress.ToString() + " " + retValue.get_str() + " mymessage").get_bool() == true); /********************************* * getaddressesbyaccount *********************************/ BOOST_CHECK_THROW(CallRPC("getaddressesbyaccount"), runtime_error); BOOST_CHECK_NO_THROW(retValue = CallRPC("getaddressesbyaccount " + strAccount)); Array arr = retValue.get_array(); BOOST_CHECK(arr.size() > 0); BOOST_CHECK(CBitcoinAddress(arr[0].get_str()).Get() == demoAddress.Get()); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Changed mixed indentation to four spaces<commit_after>// Copyright (c) 2013-2014 The Bitcoin Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcclient.h" #include "rpcserver.h" #include "base58.h" #include "wallet.h" #include <boost/algorithm/string.hpp> #include <boost/test/unit_test.hpp> using namespace std; using namespace json_spirit; extern Array createArgs(int nRequired, const char* address1 = NULL, const char* address2 = NULL); extern Value CallRPC(string args); extern CWallet* pwalletMain; BOOST_AUTO_TEST_SUITE(rpc_wallet_tests) BOOST_AUTO_TEST_CASE(rpc_addmultisig) { LOCK(pwalletMain->cs_wallet); rpcfn_type addmultisig = tableRPC["addmultisigaddress"]->actor; // old, 65-byte-long: const char address1Hex[] = "0434e3e09f49ea168c5bbf53f877ff4206923858aab7c7e1df25bc263978107c95e35065a27ef6f1b27222db0ec97e0e895eaca603d3ee0d4c060ce3d8a00286c8"; // new, compressed: const char address2Hex[] = "0388c2037017c62240b6b72ac1a2a5f94da790596ebd06177c8572752922165cb4"; Value v; CBitcoinAddress address; BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex), false)); address.SetString(v.get_str()); BOOST_CHECK(address.IsValid() && address.IsScript()); BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex, address2Hex), false)); address.SetString(v.get_str()); BOOST_CHECK(address.IsValid() && address.IsScript()); BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(2, address1Hex, address2Hex), false)); address.SetString(v.get_str()); BOOST_CHECK(address.IsValid() && address.IsScript()); BOOST_CHECK_THROW(addmultisig(createArgs(0), false), runtime_error); BOOST_CHECK_THROW(addmultisig(createArgs(1), false), runtime_error); BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), runtime_error); BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), runtime_error); BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), runtime_error); string short1(address1Hex, address1Hex + sizeof(address1Hex) - 2); // last byte missing BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), runtime_error); string short2(address1Hex + 1, address1Hex + sizeof(address1Hex)); // first byte missing BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), runtime_error); } BOOST_AUTO_TEST_CASE(rpc_wallet) { // Test RPC calls for various wallet statistics Value r; LOCK2(cs_main, pwalletMain->cs_wallet); CPubKey demoPubkey = pwalletMain->GenerateNewKey(); CBitcoinAddress demoAddress = CBitcoinAddress(CTxDestination(demoPubkey.GetID())); Value retValue; string strAccount = "walletDemoAccount"; string strPurpose = "receive"; BOOST_CHECK_NO_THROW({ /*Initialize Wallet with an account */ CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; account.vchPubKey = demoPubkey; pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, strPurpose); walletdb.WriteAccount(strAccount, account); }); CPubKey setaccountDemoPubkey = pwalletMain->GenerateNewKey(); CBitcoinAddress setaccountDemoAddress = CBitcoinAddress(CTxDestination(setaccountDemoPubkey.GetID())); /********************************* * setaccount *********************************/ BOOST_CHECK_NO_THROW(CallRPC("setaccount " + setaccountDemoAddress.ToString() + " nullaccount")); /* 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ is not owned by the test wallet. */ BOOST_CHECK_THROW(CallRPC("setaccount 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ nullaccount"), runtime_error); BOOST_CHECK_THROW(CallRPC("setaccount"), runtime_error); /* 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X (33 chars) is an illegal address (should be 34 chars) */ BOOST_CHECK_THROW(CallRPC("setaccount 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X nullaccount"), runtime_error); /********************************* * listunspent *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listunspent")); BOOST_CHECK_THROW(CallRPC("listunspent string"), runtime_error); BOOST_CHECK_THROW(CallRPC("listunspent 0 string"), runtime_error); BOOST_CHECK_THROW(CallRPC("listunspent 0 1 not_array"), runtime_error); BOOST_CHECK_THROW(CallRPC("listunspent 0 1 [] extra"), runtime_error); BOOST_CHECK_NO_THROW(r = CallRPC("listunspent 0 1 []")); BOOST_CHECK(r.get_array().empty()); /********************************* * listreceivedbyaddress *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress")); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0")); BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress not_int"), runtime_error); BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 not_bool"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0 true")); BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 true extra"), runtime_error); /********************************* * listreceivedbyaccount *********************************/ BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount")); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0")); BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount not_int"), runtime_error); BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 not_bool"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0 true")); BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 true extra"), runtime_error); /********************************* * getrawchangeaddress *********************************/ BOOST_CHECK_NO_THROW(CallRPC("getrawchangeaddress")); /********************************* * getnewaddress *********************************/ BOOST_CHECK_NO_THROW(CallRPC("getnewaddress")); BOOST_CHECK_NO_THROW(CallRPC("getnewaddress getnewaddress_demoaccount")); /********************************* * getaccountaddress *********************************/ BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress \"\"")); BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress accountThatDoesntExists")); // Should generate a new account BOOST_CHECK_NO_THROW(retValue = CallRPC("getaccountaddress " + strAccount)); BOOST_CHECK(CBitcoinAddress(retValue.get_str()).Get() == demoAddress.Get()); /********************************* * getaccount *********************************/ BOOST_CHECK_THROW(CallRPC("getaccount"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("getaccount " + demoAddress.ToString())); /********************************* * signmessage + verifymessage *********************************/ BOOST_CHECK_NO_THROW(retValue = CallRPC("signmessage " + demoAddress.ToString() + " mymessage")); BOOST_CHECK_THROW(CallRPC("signmessage"), runtime_error); /* Should throw error because this address is not loaded in the wallet */ BOOST_CHECK_THROW(CallRPC("signmessage 1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ mymessage"), runtime_error); /* missing arguments */ BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString()), runtime_error); BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str()), runtime_error); /* Illegal address */ BOOST_CHECK_THROW(CallRPC("verifymessage 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X " + retValue.get_str() + " mymessage"), runtime_error); /* wrong address */ BOOST_CHECK(CallRPC("verifymessage 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ " + retValue.get_str() + " mymessage").get_bool() == false); /* Correct address and signature but wrong message */ BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " wrongmessage").get_bool() == false); /* Correct address, message and signature*/ BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " mymessage").get_bool() == true); /********************************* * getaddressesbyaccount *********************************/ BOOST_CHECK_THROW(CallRPC("getaddressesbyaccount"), runtime_error); BOOST_CHECK_NO_THROW(retValue = CallRPC("getaddressesbyaccount " + strAccount)); Array arr = retValue.get_array(); BOOST_CHECK(arr.size() > 0); BOOST_CHECK(CBitcoinAddress(arr[0].get_str()).Get() == demoAddress.Get()); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include "CppUnitTest.h" #include <string> #include <vector> using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace std; namespace algo { template<class Traits> class tokens { vector<typename Traits::type> tokens_; public: bool empty() const { return tokens_.size() == 0; } void from_string(string s) { tokens_.push_back(Traits::tokenize(s)); } }; } namespace algo { namespace spec { struct test_token_traits { struct s {}; typedef s type; static s tokenize(const string&) { return s(); } }; typedef tokens<test_token_traits> test_tokens; TEST_CLASS(can_recognize_tokens) { public: TEST_METHOD(should_not_have_any_tokens_when_default_constructed) { test_tokens testTokens; Assert::IsTrue(testTokens.empty()); } TEST_METHOD(should_recognize_a_token) { test_tokens testTokens; testTokens.from_string("s"); Assert::IsFalse(testTokens.empty()); } }; }} <commit_msg>test rename<commit_after>#include "CppUnitTest.h" #include <string> #include <vector> using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace std; namespace algo { template<class Traits> class tokens { vector<typename Traits::type> tokens_; public: bool empty() const { return tokens_.size() == 0; } void from_string(string s) { tokens_.push_back(Traits::tokenize(s)); } }; } namespace algo { namespace spec { struct test_token_traits { struct s {}; typedef s type; static s tokenize(const string&) { return s(); } }; typedef tokens<test_token_traits> test_tokens; TEST_CLASS(can_recognize_tokens) { public: TEST_METHOD(should_not_have_any_tokens_when_default_constructed) { test_tokens testTokens; Assert::IsTrue(testTokens.empty()); } TEST_METHOD(should_recognize_a_token_in_a_string) { test_tokens testTokens; testTokens.from_string("s"); Assert::IsFalse(testTokens.empty()); } }; }} <|endoftext|>
<commit_before>/* * Server.cpp * * Created on: 2009-09-13 * Author: chudy */ #include "network/Server.h" #include "common.h" #include "network/events.h" Server::Server(int p_port) : m_raceServer(this) { m_slots.connect(m_gameServer.sig_client_connected(), this, &Server::slotClientConnected); m_slots.connect(m_gameServer.sig_client_disconnected(), this, &Server::slotClientDisconnected); m_slots.connect(m_gameServer.sig_event_received(), this, &Server::slotEventArrived); m_gameServer.start(CL_StringHelp::int_to_local8(p_port)); // TESTING m_raceServer.initialize(); } Server::~Server() { m_gameServer.stop(); } void Server::update(int p_timeElapsed) { // m_gameServer.process_events(); } void Server::slotClientConnected(CL_NetGameConnection *p_netGameConnection) { cl_log_event("network", "Player %1 is connected", (unsigned) p_netGameConnection); Player *player = new Player(); m_connections[p_netGameConnection] = player; // emit the signal m_signalPlayerConnected.invoke(p_netGameConnection, player); } void Server::slotClientDisconnected(CL_NetGameConnection *p_netGameConnection) { cl_log_event("network", "Player %1 disconnects", m_connections[p_netGameConnection]->getName().empty() ? CL_StringHelp::uint_to_local8((unsigned) p_netGameConnection) : m_connections[p_netGameConnection]->getName()); std::map<CL_NetGameConnection*, Player*>::iterator itor = m_connections.find(p_netGameConnection); if (itor != m_connections.end()) { Player* player = itor->second; // emit the signal m_signalPlayerDisconnected.invoke(p_netGameConnection, player); // cleanup delete player; m_connections.erase(itor); } } void Server::slotEventArrived(CL_NetGameConnection *p_connection, const CL_NetGameEvent &p_event) { cl_log_event("event", "Event %1 arrived", p_event.to_string()); const CL_String eventName = p_event.get_name(); const std::vector<CL_TempString> parts = CL_StringHelp::split_text(eventName, ":"); if (parts[0] == EVENT_PREFIX_GENERAL) { if (eventName == EVENT_HI) { handleHiEvent(p_connection, p_event); return; } } else if (parts[0] == EVENT_PREFIX_RACE) { m_raceServer.handleEvent(p_connection, p_event); return; } cl_log_event("event", "Event %1 remains unhandled", p_event.to_string()); } void Server::handleHiEvent(CL_NetGameConnection *p_connection, const CL_NetGameEvent &p_event) { const CL_String playerName = p_event.get_argument(0); if (playerName.empty()) { cl_log_event("error", "Protocol error while handling %1 event", p_event.to_string()); return; } // check availability bool nameAvailable = true; for ( std::map<CL_NetGameConnection*, Player*>::const_iterator itor = m_connections.begin(); itor != m_connections.end(); ++itor ) { if (itor->second->getName() == playerName) { nameAvailable = false; } } if (!nameAvailable) { // refuse of nick set reply(p_connection, CL_NetGameEvent(EVENT_PLAYER_NICK_IN_USE)); cl_log_event("event", "Name '%1' already in use for player '%2'", playerName, (unsigned) p_connection); } else { // resend player's connection event m_connections[p_connection]->setName(playerName); send(CL_NetGameEvent(EVENT_PLAYER_CONNECTED, playerName), p_connection); cl_log_event("event", "Player %1 is now known as '%2'", (unsigned) p_connection, playerName); // and send him the list of other players std::pair<CL_NetGameConnection*, Player*> pair; foreach(pair, m_connections) { if (pair.first == p_connection) { continue; } reply(p_connection, CL_NetGameEvent(EVENT_PLAYER_CONNECTED, pair.second->getName())); } } } void Server::reply(CL_NetGameConnection *p_connection, const CL_NetGameEvent &p_event) { p_connection->send_event(p_event); } void Server::send(const CL_NetGameEvent &p_event, const CL_NetGameConnection* p_ignore) { std::pair<CL_NetGameConnection*, Player*> pair; foreach(pair, m_connections) { if (pair.first != p_ignore) { pair.first->send_event(p_event); } } } void Server::prepareRace() { } <commit_msg>* Little readability correction[C<commit_after>/* * Server.cpp * * Created on: 2009-09-13 * Author: chudy */ #include "network/Server.h" #include "common.h" #include "network/events.h" Server::Server(int p_port) : m_raceServer(this) { m_slots.connect(m_gameServer.sig_client_connected(), this, &Server::slotClientConnected); m_slots.connect(m_gameServer.sig_client_disconnected(), this, &Server::slotClientDisconnected); m_slots.connect(m_gameServer.sig_event_received(), this, &Server::slotEventArrived); m_gameServer.start(CL_StringHelp::int_to_local8(p_port)); // TESTING m_raceServer.initialize(); } Server::~Server() { m_gameServer.stop(); } void Server::update(int p_timeElapsed) { // m_gameServer.process_events(); } void Server::slotClientConnected(CL_NetGameConnection *p_netGameConnection) { cl_log_event("network", "Player %1 is connected", (unsigned) p_netGameConnection); Player *player = new Player(); m_connections[p_netGameConnection] = player; // emit the signal m_signalPlayerConnected.invoke(p_netGameConnection, player); } void Server::slotClientDisconnected(CL_NetGameConnection *p_netGameConnection) { cl_log_event("network", "Player %1 disconnects", m_connections[p_netGameConnection]->getName().empty() ? CL_StringHelp::uint_to_local8((unsigned) p_netGameConnection) : m_connections[p_netGameConnection]->getName()); std::map<CL_NetGameConnection*, Player*>::iterator itor = m_connections.find(p_netGameConnection); if (itor != m_connections.end()) { Player* player = itor->second; // emit the signal m_signalPlayerDisconnected.invoke(p_netGameConnection, player); // cleanup delete player; m_connections.erase(itor); } } void Server::slotEventArrived(CL_NetGameConnection *p_connection, const CL_NetGameEvent &p_event) { cl_log_event("event", "Event %1 arrived", p_event.to_string()); const CL_String eventName = p_event.get_name(); const std::vector<CL_TempString> parts = CL_StringHelp::split_text(eventName, ":"); if (parts[0] == EVENT_PREFIX_GENERAL) { if (eventName == EVENT_HI) { handleHiEvent(p_connection, p_event); return; } } else if (parts[0] == EVENT_PREFIX_RACE) { m_raceServer.handleEvent(p_connection, p_event); return; } cl_log_event("event", "Event %1 remains unhandled", p_event.to_string()); } void Server::handleHiEvent(CL_NetGameConnection *p_connection, const CL_NetGameEvent &p_event) { const CL_String playerName = p_event.get_argument(0); if (playerName.empty()) { cl_log_event("error", "Protocol error while handling %1 event", p_event.to_string()); return; } // check availability bool nameAvailable = true; std::pair<CL_NetGameConnection*, Player*> pair; foreach (pair, m_connections) { if (pair.second->getName() == playerName) { nameAvailable = false; } } if (!nameAvailable) { // refuse of nick set reply(p_connection, CL_NetGameEvent(EVENT_PLAYER_NICK_IN_USE)); cl_log_event("event", "Name '%1' already in use for player '%2'", playerName, (unsigned) p_connection); } else { // resend player's connection event m_connections[p_connection]->setName(playerName); send(CL_NetGameEvent(EVENT_PLAYER_CONNECTED, playerName), p_connection); cl_log_event("event", "Player %1 is now known as '%2'", (unsigned) p_connection, playerName); // and send him the list of other players std::pair<CL_NetGameConnection*, Player*> pair; foreach(pair, m_connections) { if (pair.first == p_connection) { continue; } CL_NetGameEvent replyEvent(EVENT_PLAYER_CONNECTED, pair.second->getName()); reply(p_connection, replyEvent); } } } void Server::reply(CL_NetGameConnection *p_connection, const CL_NetGameEvent &p_event) { p_connection->send_event(p_event); } void Server::send(const CL_NetGameEvent &p_event, const CL_NetGameConnection* p_ignore) { std::pair<CL_NetGameConnection*, Player*> pair; foreach(pair, m_connections) { if (pair.first != p_ignore) { pair.first->send_event(p_event); } } } void Server::prepareRace() { } <|endoftext|>
<commit_before>/*$Id$ * * This source file is a part of the Berlin Project. * Copyright (C) 1998 Graydon Hoare <graydon@pobox.com> * Copyright (C) 2000 Stefan Seefeld <stefan@berlin-consortium.org> * http://www.berlin-consortium.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, * MA 02139, USA. */ #ifndef _ServerImpl_hh #define _ServerImpl_hh #include <Warsaw/config.hh> #include <Warsaw/Server.hh> #include <Warsaw/Graphic.hh> #include <Berlin/KitImpl.hh> #include <Prague/Sys/Thread.hh> #include <Prague/Sys/Plugin.hh> #include <vector> #include <string> #include <map> class ServerContextImpl; //. the Server just hands out new ServerContexts to //. people who are connecting. it might want to do some checking on //. the incoming ClientContext's credentials, but at the moment it doesn't. class ServerImpl : public virtual POA_Warsaw::Server, public virtual PortableServer::RefCountServantBase { friend class ServerContextImpl; typedef std::vector<ServerContextImpl *> clist_t; typedef std::vector<Prague::Plugin<KitImpl> *> pmap_t; typedef std::vector<KitImpl *> kmap_t; typedef std::map<std::string, CORBA::Object_var> smap_t; typedef std::multimap<std::string, Warsaw::Kit::PropertySeq_var> PluginList; public: //. Create() can be called once only! It creates the one server-object. static ServerImpl *create(const CORBA::PolicyList &); //. Get a reference to the server in use. static ServerImpl *instance(); //. Create a ServerContext. This is what is called by a client that //. wants to connect to this server. A ServerContext holds all objects //. generated by a client and gets deleted (destructing all those objects) //. as soon as the client terminated (or the server is no longer //. able to ping the client). virtual Warsaw::ServerContext_ptr create_server_context(Warsaw::ClientContext_ptr c) throw (Warsaw::SecurityException); //. Set_singleton() 'publishes' a given Object under a given name. //. Clients then can request access to this object with get_singleton. //. The server makes sure that there are no two objects by the same name, //. throwing an SingletonFailureException as soon as someone tries to //. give a name allready known to the server, virtual void set_singleton(const char *, CORBA::Object_ptr) throw (Warsaw::SecurityException, Warsaw::SingletonFailureException); //. This method removes the object of the given name from the //. list of known singletons. It does not destruct the object virtual void remove_singleton(const char *) throw (Warsaw::SecurityException, Warsaw::SingletonFailureException); virtual CORBA::Object_ptr get_singleton(const char *) throw (Warsaw::SecurityException, Warsaw::SingletonFailureException); //. Finds the requested Kit and returns a reference to it. template <class K> typename K::_ptr_type resolve(const char *, const Warsaw::Kit::PropertySeq &, PortableServer::POA_ptr); //. Starts the server. void start(); //. Stops the server. void stop(); //. Pings all ServerContexts and destroys those that do not //. respond (aka. crashed). void ping(); //. This scans all directories given as modulepath in berlinrc for Kits //. and loads the whole lot of them. void scan(const std::string &); //. Deletes all known Kits. void clear(); //. Returns a list of all known Pluginnames (kits) and their properties. PluginList list(); protected: //. Finds the requested kit and loads it. This is a helper function only. //. Use resolve, KitImpl *create(const char *, const Warsaw::Kit::PropertySeq &, PortableServer::POA_ptr); private: ServerImpl(const CORBA::PolicyList &); //. Called every second to ping the clients. static void *run(void *); //. Destroys a given Servercontext (and with that the client's resources //. in this server). static void destroy_context(ServerContextImpl *); CORBA::PolicyList _policies; Prague::Thread _thread; Prague::Mutex _mutex; smap_t _singletons; clist_t _contexts; pmap_t _plugins; kmap_t _kits; static ServerImpl *_server; }; template <class K> typename K::_ptr_type ServerImpl::resolve(const char *type, const Warsaw::Kit::PropertySeq &properties, PortableServer::POA_ptr poa) { KitImpl *kit = create(type, properties, poa); if (!kit) return K::_nil(); typename K::_var_type reference; try { reference = K::_narrow(Warsaw::Kit_var(kit->_this())); } catch (CORBA::Exception &e) { std::cerr << "Cannot narrow reference: " << e << std::endl; return K::_nil(); } if (CORBA::is_nil(reference)) { std::cerr << "Reference has incorrect type" << std::endl; return K::_nil(); } _kits.push_back(kit); return reference._retn(); } #endif <commit_msg>I accidentally moved a typedef into private. Dunno why that happened. Sorry for any inconvinience that might have caused.<commit_after>/*$Id$ * * This source file is a part of the Berlin Project. * Copyright (C) 1998 Graydon Hoare <graydon@pobox.com> * Copyright (C) 2000 Stefan Seefeld <stefan@berlin-consortium.org> * http://www.berlin-consortium.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, * MA 02139, USA. */ #ifndef _ServerImpl_hh #define _ServerImpl_hh #include <Warsaw/config.hh> #include <Warsaw/Server.hh> #include <Warsaw/Graphic.hh> #include <Berlin/KitImpl.hh> #include <Prague/Sys/Thread.hh> #include <Prague/Sys/Plugin.hh> #include <vector> #include <string> #include <map> class ServerContextImpl; //. the Server just hands out new ServerContexts to //. people who are connecting. it might want to do some checking on //. the incoming ClientContext's credentials, but at the moment it doesn't. class ServerImpl : public virtual POA_Warsaw::Server, public virtual PortableServer::RefCountServantBase { friend class ServerContextImpl; typedef std::vector<ServerContextImpl *> clist_t; typedef std::vector<Prague::Plugin<KitImpl> *> pmap_t; typedef std::vector<KitImpl *> kmap_t; typedef std::map<std::string, CORBA::Object_var> smap_t; public: typedef std::multimap<std::string, Warsaw::Kit::PropertySeq_var> PluginList; //. Create() can be called once only! It creates the one server-object. static ServerImpl *create(const CORBA::PolicyList &); //. Get a reference to the server in use. static ServerImpl *instance(); //. Create a ServerContext. This is what is called by a client that //. wants to connect to this server. A ServerContext holds all objects //. generated by a client and gets deleted (destructing all those objects) //. as soon as the client terminated (or the server is no longer //. able to ping the client). virtual Warsaw::ServerContext_ptr create_server_context(Warsaw::ClientContext_ptr c) throw (Warsaw::SecurityException); //. Set_singleton() 'publishes' a given Object under a given name. //. Clients then can request access to this object with get_singleton. //. The server makes sure that there are no two objects by the same name, //. throwing an SingletonFailureException as soon as someone tries to //. give a name allready known to the server, virtual void set_singleton(const char *, CORBA::Object_ptr) throw (Warsaw::SecurityException, Warsaw::SingletonFailureException); //. This method removes the object of the given name from the //. list of known singletons. It does not destruct the object virtual void remove_singleton(const char *) throw (Warsaw::SecurityException, Warsaw::SingletonFailureException); virtual CORBA::Object_ptr get_singleton(const char *) throw (Warsaw::SecurityException, Warsaw::SingletonFailureException); //. Finds the requested Kit and returns a reference to it. template <class K> typename K::_ptr_type resolve(const char *, const Warsaw::Kit::PropertySeq &, PortableServer::POA_ptr); //. Starts the server. void start(); //. Stops the server. void stop(); //. Pings all ServerContexts and destroys those that do not //. respond (aka. crashed). void ping(); //. This scans all directories given as modulepath in berlinrc for Kits //. and loads the whole lot of them. void scan(const std::string &); //. Deletes all known Kits. void clear(); //. Returns a list of all known Pluginnames (kits) and their properties. PluginList list(); protected: //. Finds the requested kit and loads it. This is a helper function only. //. Use resolve, KitImpl *create(const char *, const Warsaw::Kit::PropertySeq &, PortableServer::POA_ptr); private: ServerImpl(const CORBA::PolicyList &); //. Called every second to ping the clients. static void *run(void *); //. Destroys a given Servercontext (and with that the client's resources //. in this server). static void destroy_context(ServerContextImpl *); CORBA::PolicyList _policies; Prague::Thread _thread; Prague::Mutex _mutex; smap_t _singletons; clist_t _contexts; pmap_t _plugins; kmap_t _kits; static ServerImpl *_server; }; template <class K> typename K::_ptr_type ServerImpl::resolve(const char *type, const Warsaw::Kit::PropertySeq &properties, PortableServer::POA_ptr poa) { KitImpl *kit = create(type, properties, poa); if (!kit) return K::_nil(); typename K::_var_type reference; try { reference = K::_narrow(Warsaw::Kit_var(kit->_this())); } catch (CORBA::Exception &e) { std::cerr << "Cannot narrow reference: " << e << std::endl; return K::_nil(); } if (CORBA::is_nil(reference)) { std::cerr << "Reference has incorrect type" << std::endl; return K::_nil(); } _kits.push_back(kit); return reference._retn(); } #endif <|endoftext|>
<commit_before>#include "shared.hh" #include "local-store.hh" #include "util.hh" #include "serialise.hh" #include "worker-protocol.hh" #include "archive.hh" #include <iostream> using namespace nix; Path readStorePath(Source & from) { Path path = readString(from); assertStorePath(path); return path; } PathSet readStorePaths(Source & from) { PathSet paths = readStringSet(from); for (PathSet::iterator i = paths.begin(); i != paths.end(); ++i) assertStorePath(*i); return paths; } void processConnection(Source & from, Sink & to) { store = boost::shared_ptr<StoreAPI>(new LocalStore(true)); unsigned int magic = readInt(from); if (magic != WORKER_MAGIC_1) throw Error("protocol mismatch"); writeInt(WORKER_MAGIC_2, to); debug("greeting exchanged"); bool quit = false; unsigned int opCount = 0; do { WorkerOp op = (WorkerOp) readInt(from); opCount++; switch (op) { case wopQuit: { /* Close the database. */ store.reset((StoreAPI *) 0); writeInt(1, to); quit = true; break; } case wopIsValidPath: { Path path = readStorePath(from); writeInt(store->isValidPath(path), to); break; } case wopHasSubstitutes: { Path path = readStorePath(from); writeInt(store->hasSubstitutes(path), to); break; } case wopQueryPathHash: { Path path = readStorePath(from); writeString(printHash(store->queryPathHash(path)), to); break; } case wopQueryReferences: case wopQueryReferrers: { Path path = readStorePath(from); PathSet paths; if (op == wopQueryReferences) store->queryReferences(path, paths); else store->queryReferrers(path, paths); writeStringSet(paths, to); break; } case wopAddToStore: { /* !!! uberquick hack */ string baseName = readString(from); bool fixed = readInt(from) == 1; bool recursive = readInt(from) == 1; string hashAlgo = readString(from); Path tmp = createTempDir(); Path tmp2 = tmp + "/" + baseName; restorePath(tmp2, from); writeString(store->addToStore(tmp2, fixed, recursive, hashAlgo), to); deletePath(tmp); break; } case wopAddTextToStore: { string suffix = readString(from); string s = readString(from); PathSet refs = readStorePaths(from); writeString(store->addTextToStore(suffix, s, refs), to); break; } case wopBuildDerivations: { PathSet drvs = readStorePaths(from); store->buildDerivations(drvs); writeInt(1, to); break; } case wopEnsurePath: { Path path = readStorePath(from); store->ensurePath(path); writeInt(1, to); break; } case wopAddTempRoot: { Path path = readStorePath(from); store->addTempRoot(path); writeInt(1, to); break; } case wopSyncWithGC: { store->syncWithGC(); writeInt(1, to); break; } default: throw Error(format("invalid operation %1%") % op); } } while (!quit); printMsg(lvlError, format("%1% worker operations") % opCount); } void run(Strings args) { bool slave = false; bool daemon = false; for (Strings::iterator i = args.begin(); i != args.end(); ) { string arg = *i++; if (arg == "--slave") slave = true; if (arg == "--daemon") daemon = true; } if (slave) { FdSource source(STDIN_FILENO); FdSink sink(STDOUT_FILENO); processConnection(source, sink); } else if (daemon) throw Error("daemon mode not implemented"); else throw Error("must be run in either --slave or --daemon mode"); } #include "help.txt.hh" void printHelp() { std::cout << string((char *) helpText, sizeof helpText); } string programId = "nix-worker"; <commit_msg>* Run the worker in a separate session to prevent terminal signals from interfering.<commit_after>#include "shared.hh" #include "local-store.hh" #include "util.hh" #include "serialise.hh" #include "worker-protocol.hh" #include "archive.hh" #include <iostream> using namespace nix; Path readStorePath(Source & from) { Path path = readString(from); assertStorePath(path); return path; } PathSet readStorePaths(Source & from) { PathSet paths = readStringSet(from); for (PathSet::iterator i = paths.begin(); i != paths.end(); ++i) assertStorePath(*i); return paths; } void processConnection(Source & from, Sink & to) { store = boost::shared_ptr<StoreAPI>(new LocalStore(true)); unsigned int magic = readInt(from); if (magic != WORKER_MAGIC_1) throw Error("protocol mismatch"); writeInt(WORKER_MAGIC_2, to); debug("greeting exchanged"); bool quit = false; unsigned int opCount = 0; do { WorkerOp op = (WorkerOp) readInt(from); opCount++; switch (op) { case wopQuit: { /* Close the database. */ store.reset((StoreAPI *) 0); writeInt(1, to); quit = true; break; } case wopIsValidPath: { Path path = readStorePath(from); writeInt(store->isValidPath(path), to); break; } case wopHasSubstitutes: { Path path = readStorePath(from); writeInt(store->hasSubstitutes(path), to); break; } case wopQueryPathHash: { Path path = readStorePath(from); writeString(printHash(store->queryPathHash(path)), to); break; } case wopQueryReferences: case wopQueryReferrers: { Path path = readStorePath(from); PathSet paths; if (op == wopQueryReferences) store->queryReferences(path, paths); else store->queryReferrers(path, paths); writeStringSet(paths, to); break; } case wopAddToStore: { /* !!! uberquick hack */ string baseName = readString(from); bool fixed = readInt(from) == 1; bool recursive = readInt(from) == 1; string hashAlgo = readString(from); Path tmp = createTempDir(); Path tmp2 = tmp + "/" + baseName; restorePath(tmp2, from); writeString(store->addToStore(tmp2, fixed, recursive, hashAlgo), to); deletePath(tmp); break; } case wopAddTextToStore: { string suffix = readString(from); string s = readString(from); PathSet refs = readStorePaths(from); writeString(store->addTextToStore(suffix, s, refs), to); break; } case wopBuildDerivations: { PathSet drvs = readStorePaths(from); store->buildDerivations(drvs); writeInt(1, to); break; } case wopEnsurePath: { Path path = readStorePath(from); store->ensurePath(path); writeInt(1, to); break; } case wopAddTempRoot: { Path path = readStorePath(from); store->addTempRoot(path); writeInt(1, to); break; } case wopSyncWithGC: { store->syncWithGC(); writeInt(1, to); break; } default: throw Error(format("invalid operation %1%") % op); } } while (!quit); printMsg(lvlError, format("%1% worker operations") % opCount); } void run(Strings args) { bool slave = false; bool daemon = false; for (Strings::iterator i = args.begin(); i != args.end(); ) { string arg = *i++; if (arg == "--slave") slave = true; if (arg == "--daemon") daemon = true; } if (slave) { FdSource source(STDIN_FILENO); FdSink sink(STDOUT_FILENO); /* This prevents us from receiving signals from the terminal when we're running in setuid mode. */ if (setsid() == -1) throw SysError(format("creating a new session")); processConnection(source, sink); } else if (daemon) throw Error("daemon mode not implemented"); else throw Error("must be run in either --slave or --daemon mode"); } #include "help.txt.hh" void printHelp() { std::cout << string((char *) helpText, sizeof helpText); } string programId = "nix-worker"; <|endoftext|>
<commit_before>/********************************************************************** Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. 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 "cl_uberv2_generator.h" using namespace Baikal; CLUberV2Generator::CLUberV2Generator() { } CLUberV2Generator::~CLUberV2Generator() { } void CLUberV2Generator::AddMaterial(UberV2Material::Ptr material) { uint32_t layers = material->GetLayers(); // Check if we already have such material type processed if (m_materials.find(layers) != m_materials.end()) { return; } UberV2Sources src; MaterialGeneratePrepareInputs(material, &src); MaterialGenerateGetPdf(material, &src); MaterialGenerateSample(material, &src); MaterialGenerateGetBxDFType(material, &src); MaterialGenerateEvaluate(material, &src); m_materials[layers] = src; } void CLUberV2Generator::MaterialGeneratePrepareInputs(UberV2Material::Ptr material, UberV2Sources *sources) { static const std::string reader_function_arguments("material_attributes[offset++], dg, input_map_values, TEXTURE_ARGS"); struct LayerReader { std::string variable; std::string reader; }; // Should have same order as in ClwSceneController::WriteMaterial static const std::vector<std::pair<UberV2Material::Layers, std::vector<LayerReader>>> readers = { { UberV2Material::Layers::kEmissionLayer, { {"shader_data.emission_color", "GetInputMapFloat4"} } }, { UberV2Material::Layers::kCoatingLayer, { {"shader_data.coating_color", "GetInputMapFloat4"}, {"shader_data.coating_ior", "GetInputMapFloat"} } }, { UberV2Material::Layers::kReflectionLayer, { {"shader_data.coating_color", "GetInputMapFloat4"}, {"shader_data.coating_ior", "GetInputMapFloat"}, {"shader_data.reflection_color", "GetInputMapFloat4"}, {"shader_data.reflection_roughness", "GetInputMapFloat"}, {"shader_data.reflection_anisotropy", "GetInputMapFloat"}, {"shader_data.reflection_anisotropy_rotation", "GetInputMapFloat"}, {"shader_data.reflection_ior", "GetInputMapFloat"}, {"shader_data.reflection_metalness", "GetInputMapFloat"} } }, { UberV2Material::Layers::kDiffuseLayer, { {"shader_data.diffuse_color", "GetInputMapFloat4"} } }, { UberV2Material::Layers::kRefractionLayer, { {"shader_data.refraction_color", "GetInputMapFloat4"}, {"shader_data.refraction_roughness", "GetInputMapFloat"}, {"shader_data.refraction_ior", "GetInputMapFloat"} } }, { UberV2Material::Layers::kTransparencyLayer, { {"shader_data.transparency", "GetInputMapFloat"} } }, { UberV2Material::Layers::kShadingNormalLayer, { {"shader_data.shading_normal", "GetInputMapFloat4"}, } }, { UberV2Material::Layers::kSSSLayer, { {"shader_data.sss_absorption_color", "GetInputMapFloat4"}, {"shader_data.sss_scatter_color", "GetInputMapFloat4"}, {"shader_data.sss_subsurface_color", "GetInputMapFloat4"}, {"shader_data.sss_absorption_distance", "GetInputMapFloat"}, {"shader_data.sss_scatter_distance", "GetInputMapFloat"}, {"shader_data.sss_scatter_direction", "GetInputMapFloat"}, } } }; // Reserve 4k. This should be enought for maximum configuration sources->m_prepare_inputs.reserve(4096); // Write base code uint32_t layers = material->GetLayers(); sources->m_prepare_inputs = "UberV2ShaderData UberV2PrepareInputs" + std::to_string(layers) + "(" "DifferentialGeometry const* dg, GLOBAL InputMapData const* restrict input_map_values," "GLOBAL int const* restrict material_attributes, TEXTURE_ARG_LIST)\n" "{\n" "\tUberV2ShaderData shader_data;\n" "\tint offset = dg->mat.offset + 1;\n"; // Write code for each layer for (auto &reader: readers) { // If current layer exist in material - write it if ((layers & reader.first) == reader.first) { for (auto &r : reader.second) { sources->m_prepare_inputs += std::string("\t") + r.variable + " = " + r.reader + "(" + reader_function_arguments + ");\n"; } } } sources->m_prepare_inputs += "\treturn shader_data;\n}"; } void CLUberV2Generator::MaterialGenerateGetPdf(UberV2Material::Ptr material, UberV2Sources *sources) { } void CLUberV2Generator::MaterialGenerateSample(UberV2Material::Ptr material, UberV2Sources *sources) { uint32_t layers = material->GetLayers(); sources->m_sample = "float3 UberV2_Sample(DifferentialGeometry const* dg, float3 wi, TEXTURE_ARG_LIST, float2 sample, float3* wo, float* pdf, "UberV2ShaderData const* shader_data)\n" "{\n" "\tconst int sampledComponent = Bxdf_UberV2_GetSampledComponent(dg);\n"; soruces->m_sample += "\treturn 0.f;\n" "}\n"; } void CLUberV2Generator::MaterialGenerateGetBxDFType(UberV2Material::Ptr material, UberV2Sources *sources) { uint32_t layers = material->GetLayers(); sources->m_get_bxdf_type = "void GetMaterialBxDFType" + std::to_string(layers) + "(" "float3 wi, Sampler* sampler, SAMPLER_ARG_LIST, DifferentialGeometry* dg, UberV2ShaderData const* shader_data)\n" "{\n"; "\tint bxdf_flags = 0;\n"; // If we have layer that requires fresnel blend (reflection/refraction/coating) if ((layers & (UberV2Material::Layers::kReflectionLayer | UberV2Material::Layers::kRefractionLayer | UberV2Material::Layers::kCoatingLayer )) != 0) { sources->m_get_bxdf_type += "\tconst float ndotwi = dot(dg->n, wi);\n"; } if ((layers & UberV2Material::Layers::kEmissionLayer) == UberV2Material::Layers::kEmissionLayer) { sources->m_get_bxdf_type += "\tbxdf_flags |= kBxdfFlagsEmissive;\n"; } if ((layers & UberV2Material::Layers::kTransparencyLayer) == UberV2Material::Layers::kTransparencyLayer) { // If layer have transparency check in OpenCL if we sample it and if we sample it - return sources->m_get_bxdf_type += "\tfloat sample = Sampler_Sample1D(sampler, SAMPLER_ARGS);\n" "\tif (sample < shader_data->transparency)\n" "\t{\n" "\t\tbxdf_flags |= (kBxdfFlagsTransparency | kBxdfFlagsSingular);\n" "\t\tBxdf_SetFlags(dg, bxdf_flags);\n" "\t\tBxdf_UberV2_SetSampledComponent(dg, kBxdfUberV2SampleTransparency);\n" "\t\treturn;\n" "\t}\n"; } // Check refraction layer. If we have it and plan to sample it - set flags and sampled component if ((layers & UberV2Material::Layers::kRefractionLayer) == UberV2Material::Layers::kRefractionLayer) { sources->m_get_bxdf_type += "\tfloat sample = Sampler_Sample1D(sampler, SAMPLER_ARGS);\n" "\tconst float fresnel = CalculateFresnel(1.0f, shader_data->refraction_ior, ndotwi);\n" "\tif (sample >= fresnel)\n" "\t{\n" "\t\tBxdf_UberV2_SetSampledComponent(dg, kBxdfUberV2SampleRefraction);\n" "\t\tif (shader_data->refraction_roughness < ROUGHNESS_EPS)\n" "\t\t{\n" "\t\t\tbxdf_flags |= kBxdfFlagsSingular;\n" "\t\t}\n" "\t\tBxdf_SetFlags(dg, bxdf_flags);" "\t\treturn;\n" "\t}\n"; } sources->m_get_bxdf_type += "\tbxdf_flags |= kBxdfFlagsBrdf;\n" "\tfloat top_ior = 1.0f;\n"; if ((layers & UberV2Material::Layers::kCoatingLayer) == UberV2Material::Layers::kCoatingLayer) { sources->m_get_bxdf_type += "\tfloat sample = Sampler_Sample1D(sampler, SAMPLER_ARGS);\n" "\tconst float fresnel = CalculateFresnel(top_ior, shader_data->coating_ior, ndotwi);\n" "\tif (sample < fresnel)\n" "\t{\n" "\t\tbxdf_flags |= kBxdfFlagsSingular;\n" "\t\tBxdf_SetFlags(dg, bxdf_flags);\n" "\t\tBxdf_UberV2_SetSampledComponent(dg, kBxdfUberV2SampleCoating);\n" "\t\treturn;\n" "\t}\n" "\ttop_ior = shader_data->coating_ior;\n"; } if ((layers & UberV2Material::Layers::kReflectionLayer) == UberV2Material::Layers::kReflectionLayer) { sources->m_get_bxdf_type += "\tconst float fresnel = CalculateFresnel(top_ior, shader_data->reflection_ior, ndotwi);\n" "\tfloat sample = Sampler_Sample1D(sampler, SAMPLER_ARGS);\n" "\tif (sample < fresnel)\n" "\t{\n" "\t\tif (shader_data->reflection_roughness < ROUGHNESS_EPS)\n" "\t\t{\n" "\t\t\tbxdf_flags |= kBxdfFlagsSingular;\n" "\t\t}\n" "\t\tBxdf_UberV2_SetSampledComponent(dg, kBxdfUberV2SampleReflection);\n" "\t\tBxdf_SetFlags(dg, bxdf_flags);\n" "\t\treturn;\n" "\t}\n"; } sources->m_get_bxdf_type += "\tBxdf_UberV2_SetSampledComponent(dg, kBxdfUberV2SampleDiffuse);\n" "\tBxdf_SetFlags(dg, bxdf_flags);\n" "return;\n" "}\n"; } void CLUberV2Generator::MaterialGenerateEvaluate(UberV2Material::Ptr material, UberV2Sources *sources) { } <commit_msg>Minor fixes for MaterialGenerateSample<commit_after>/********************************************************************** Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. 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 "cl_uberv2_generator.h" using namespace Baikal; CLUberV2Generator::CLUberV2Generator() { } CLUberV2Generator::~CLUberV2Generator() { } void CLUberV2Generator::AddMaterial(UberV2Material::Ptr material) { uint32_t layers = material->GetLayers(); // Check if we already have such material type processed if (m_materials.find(layers) != m_materials.end()) { return; } UberV2Sources src; MaterialGeneratePrepareInputs(material, &src); MaterialGenerateGetPdf(material, &src); MaterialGenerateSample(material, &src); MaterialGenerateGetBxDFType(material, &src); MaterialGenerateEvaluate(material, &src); m_materials[layers] = src; } void CLUberV2Generator::MaterialGeneratePrepareInputs(UberV2Material::Ptr material, UberV2Sources *sources) { static const std::string reader_function_arguments("material_attributes[offset++], dg, input_map_values, TEXTURE_ARGS"); struct LayerReader { std::string variable; std::string reader; }; // Should have same order as in ClwSceneController::WriteMaterial static const std::vector<std::pair<UberV2Material::Layers, std::vector<LayerReader>>> readers = { { UberV2Material::Layers::kEmissionLayer, { {"shader_data.emission_color", "GetInputMapFloat4"} } }, { UberV2Material::Layers::kCoatingLayer, { {"shader_data.coating_color", "GetInputMapFloat4"}, {"shader_data.coating_ior", "GetInputMapFloat"} } }, { UberV2Material::Layers::kReflectionLayer, { {"shader_data.coating_color", "GetInputMapFloat4"}, {"shader_data.coating_ior", "GetInputMapFloat"}, {"shader_data.reflection_color", "GetInputMapFloat4"}, {"shader_data.reflection_roughness", "GetInputMapFloat"}, {"shader_data.reflection_anisotropy", "GetInputMapFloat"}, {"shader_data.reflection_anisotropy_rotation", "GetInputMapFloat"}, {"shader_data.reflection_ior", "GetInputMapFloat"}, {"shader_data.reflection_metalness", "GetInputMapFloat"} } }, { UberV2Material::Layers::kDiffuseLayer, { {"shader_data.diffuse_color", "GetInputMapFloat4"} } }, { UberV2Material::Layers::kRefractionLayer, { {"shader_data.refraction_color", "GetInputMapFloat4"}, {"shader_data.refraction_roughness", "GetInputMapFloat"}, {"shader_data.refraction_ior", "GetInputMapFloat"} } }, { UberV2Material::Layers::kTransparencyLayer, { {"shader_data.transparency", "GetInputMapFloat"} } }, { UberV2Material::Layers::kShadingNormalLayer, { {"shader_data.shading_normal", "GetInputMapFloat4"}, } }, { UberV2Material::Layers::kSSSLayer, { {"shader_data.sss_absorption_color", "GetInputMapFloat4"}, {"shader_data.sss_scatter_color", "GetInputMapFloat4"}, {"shader_data.sss_subsurface_color", "GetInputMapFloat4"}, {"shader_data.sss_absorption_distance", "GetInputMapFloat"}, {"shader_data.sss_scatter_distance", "GetInputMapFloat"}, {"shader_data.sss_scatter_direction", "GetInputMapFloat"}, } } }; // Reserve 4k. This should be enought for maximum configuration sources->m_prepare_inputs.reserve(4096); // Write base code uint32_t layers = material->GetLayers(); sources->m_prepare_inputs = "UberV2ShaderData UberV2PrepareInputs" + std::to_string(layers) + "(" "DifferentialGeometry const* dg, GLOBAL InputMapData const* restrict input_map_values," "GLOBAL int const* restrict material_attributes, TEXTURE_ARG_LIST)\n" "{\n" "\tUberV2ShaderData shader_data;\n" "\tint offset = dg->mat.offset + 1;\n"; // Write code for each layer for (auto &reader: readers) { // If current layer exist in material - write it if ((layers & reader.first) == reader.first) { for (auto &r : reader.second) { sources->m_prepare_inputs += std::string("\t") + r.variable + " = " + r.reader + "(" + reader_function_arguments + ");\n"; } } } sources->m_prepare_inputs += "\treturn shader_data;\n}"; } void CLUberV2Generator::MaterialGenerateGetPdf(UberV2Material::Ptr material, UberV2Sources *sources) { } void CLUberV2Generator::MaterialGenerateSample(UberV2Material::Ptr material, UberV2Sources *sources) { uint32_t layers = material->GetLayers(); sources->m_sample = "float3 UberV2_Sample" + std::to_string(layers) + "(DifferentialGeometry const* dg, float3 wi, TEXTURE_ARG_LIST, float2 sample, float3* wo, float* pdf," "UberV2ShaderData const* shader_data)\n" "{\n" "\tconst int sampledComponent = Bxdf_UberV2_GetSampledComponent(dg);\n"; sources->m_sample += "\treturn 0.f;\n" "}\n"; } void CLUberV2Generator::MaterialGenerateGetBxDFType(UberV2Material::Ptr material, UberV2Sources *sources) { uint32_t layers = material->GetLayers(); sources->m_get_bxdf_type = "void GetMaterialBxDFType" + std::to_string(layers) + "(" "float3 wi, Sampler* sampler, SAMPLER_ARG_LIST, DifferentialGeometry* dg, UberV2ShaderData const* shader_data)\n" "{\n"; "\tint bxdf_flags = 0;\n"; // If we have layer that requires fresnel blend (reflection/refraction/coating) if ((layers & (UberV2Material::Layers::kReflectionLayer | UberV2Material::Layers::kRefractionLayer | UberV2Material::Layers::kCoatingLayer )) != 0) { sources->m_get_bxdf_type += "\tconst float ndotwi = dot(dg->n, wi);\n"; } if ((layers & UberV2Material::Layers::kEmissionLayer) == UberV2Material::Layers::kEmissionLayer) { sources->m_get_bxdf_type += "\tbxdf_flags |= kBxdfFlagsEmissive;\n"; } if ((layers & UberV2Material::Layers::kTransparencyLayer) == UberV2Material::Layers::kTransparencyLayer) { // If layer have transparency check in OpenCL if we sample it and if we sample it - return sources->m_get_bxdf_type += "\tfloat sample = Sampler_Sample1D(sampler, SAMPLER_ARGS);\n" "\tif (sample < shader_data->transparency)\n" "\t{\n" "\t\tbxdf_flags |= (kBxdfFlagsTransparency | kBxdfFlagsSingular);\n" "\t\tBxdf_SetFlags(dg, bxdf_flags);\n" "\t\tBxdf_UberV2_SetSampledComponent(dg, kBxdfUberV2SampleTransparency);\n" "\t\treturn;\n" "\t}\n"; } // Check refraction layer. If we have it and plan to sample it - set flags and sampled component if ((layers & UberV2Material::Layers::kRefractionLayer) == UberV2Material::Layers::kRefractionLayer) { sources->m_get_bxdf_type += "\tfloat sample = Sampler_Sample1D(sampler, SAMPLER_ARGS);\n" "\tconst float fresnel = CalculateFresnel(1.0f, shader_data->refraction_ior, ndotwi);\n" "\tif (sample >= fresnel)\n" "\t{\n" "\t\tBxdf_UberV2_SetSampledComponent(dg, kBxdfUberV2SampleRefraction);\n" "\t\tif (shader_data->refraction_roughness < ROUGHNESS_EPS)\n" "\t\t{\n" "\t\t\tbxdf_flags |= kBxdfFlagsSingular;\n" "\t\t}\n" "\t\tBxdf_SetFlags(dg, bxdf_flags);" "\t\treturn;\n" "\t}\n"; } sources->m_get_bxdf_type += "\tbxdf_flags |= kBxdfFlagsBrdf;\n" "\tfloat top_ior = 1.0f;\n"; if ((layers & UberV2Material::Layers::kCoatingLayer) == UberV2Material::Layers::kCoatingLayer) { sources->m_get_bxdf_type += "\tfloat sample = Sampler_Sample1D(sampler, SAMPLER_ARGS);\n" "\tconst float fresnel = CalculateFresnel(top_ior, shader_data->coating_ior, ndotwi);\n" "\tif (sample < fresnel)\n" "\t{\n" "\t\tbxdf_flags |= kBxdfFlagsSingular;\n" "\t\tBxdf_SetFlags(dg, bxdf_flags);\n" "\t\tBxdf_UberV2_SetSampledComponent(dg, kBxdfUberV2SampleCoating);\n" "\t\treturn;\n" "\t}\n" "\ttop_ior = shader_data->coating_ior;\n"; } if ((layers & UberV2Material::Layers::kReflectionLayer) == UberV2Material::Layers::kReflectionLayer) { sources->m_get_bxdf_type += "\tconst float fresnel = CalculateFresnel(top_ior, shader_data->reflection_ior, ndotwi);\n" "\tfloat sample = Sampler_Sample1D(sampler, SAMPLER_ARGS);\n" "\tif (sample < fresnel)\n" "\t{\n" "\t\tif (shader_data->reflection_roughness < ROUGHNESS_EPS)\n" "\t\t{\n" "\t\t\tbxdf_flags |= kBxdfFlagsSingular;\n" "\t\t}\n" "\t\tBxdf_UberV2_SetSampledComponent(dg, kBxdfUberV2SampleReflection);\n" "\t\tBxdf_SetFlags(dg, bxdf_flags);\n" "\t\treturn;\n" "\t}\n"; } sources->m_get_bxdf_type += "\tBxdf_UberV2_SetSampledComponent(dg, kBxdfUberV2SampleDiffuse);\n" "\tBxdf_SetFlags(dg, bxdf_flags);\n" "return;\n" "}\n"; } void CLUberV2Generator::MaterialGenerateEvaluate(UberV2Material::Ptr material, UberV2Sources *sources) { } <|endoftext|>
<commit_before>// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /* * Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia * Author: Lorenzo Natale * email: lorenzo.natale@iit.it * Permission is granted to copy, distribute, and/or modify this program * under the terms of the GNU General Public License, version 2 or any * later version published by the Free Software Foundation. * * A copy of the license can be found at * http://www.robotcub.org/icub/license/gpl.txt * * 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 */ #include "TestCamera.h" #include <yarp/os/BufferedPort.h> #include <yarp/sig/Image.h> #include <yarp/os/Network.h> using namespace yarp::os; using namespace yarp::sig; // these values can be parameters if needed but better to keep it simple const int TIME=3; const int FREQUENCY=30; const int FRAMES_TOLERANCE=10; using namespace Logger; TestCamera::TestCamera(yarp::os::Property& configuration) : UnitTest(configuration) { } TestCamera::~TestCamera() { } bool TestCamera::init(yarp::os::Property &configuration) { if (!configuration.check("portname")) return false; portname=configuration.find("portname").asString(); return true; } bool TestCamera::run() { BufferedPort<Image> port; if (!port.open("/iCubTest/camera")) { checkTrue(false, "opening port, is YARP network working?"); return true; } Logger::report("connecting from %s to %s\n", port.getName().c_str(), portname.c_str()); if (!Network::connect(portname, port.getName())) { checkTrue(false, "could not connect to remote port, camera unavailable"); return true; } printf("Reading images..."); double timeStart=yarp::os::Time::now(); double timeNow=timeStart; int frames=0; while(timeNow<timeStart+TIME) { Image *image=port.read(false); if (image!=0) frames++; yarp::os::Time::delay(0.01); timeNow=yarp::os::Time::now(); printf("."); } printf("\n"); int expectedFrames=TIME*FREQUENCY; Logger::report("Received %d frames, expecting %d\n", frames, expectedFrames); checkTrue((abs(frames-expectedFrames)<FRAMES_TOLERANCE), "checking number of received frames"); return true; } <commit_msg>speed up camera test<commit_after>// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /* * Copyright (C) 2014 iCub Facility, Istituto Italiano di Tecnologia * Author: Lorenzo Natale * email: lorenzo.natale@iit.it * Permission is granted to copy, distribute, and/or modify this program * under the terms of the GNU General Public License, version 2 or any * later version published by the Free Software Foundation. * * A copy of the license can be found at * http://www.robotcub.org/icub/license/gpl.txt * * 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 */ #include "TestCamera.h" #include <yarp/os/BufferedPort.h> #include <yarp/sig/Image.h> #include <yarp/os/Network.h> using namespace yarp::os; using namespace yarp::sig; // these values can be parameters if needed but better to keep it simple const int TIME=1; const int FREQUENCY=30; const int FRAMES_TOLERANCE=5; using namespace Logger; TestCamera::TestCamera(yarp::os::Property& configuration) : UnitTest(configuration) { } TestCamera::~TestCamera() { } bool TestCamera::init(yarp::os::Property &configuration) { if (!configuration.check("portname")) return false; portname=configuration.find("portname").asString(); return true; } bool TestCamera::run() { BufferedPort<Image> port; if (!port.open("/iCubTest/camera")) { checkTrue(false, "opening port, is YARP network working?"); return true; } Logger::report("connecting from %s to %s\n", port.getName().c_str(), portname.c_str()); if (!Network::connect(portname, port.getName())) { checkTrue(false, "could not connect to remote port, camera unavailable"); return true; } printf("Reading images..."); double timeStart=yarp::os::Time::now(); double timeNow=timeStart; int frames=0; while(timeNow<timeStart+TIME) { Image *image=port.read(false); if (image!=0) frames++; yarp::os::Time::delay(0.01); timeNow=yarp::os::Time::now(); printf("."); } printf("\n"); int expectedFrames=TIME*FREQUENCY; Logger::report("Received %d frames, expecting %d\n", frames, expectedFrames); checkTrue((abs(frames-expectedFrames)<FRAMES_TOLERANCE), "checking number of received frames"); return true; } <|endoftext|>
<commit_before>/* * Copyright (C) 2013 midnightBITS * * 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 "pch.h" #include <handlers.hpp> #include <utils.hpp> #include "api_handler.hpp" namespace FastCGI { namespace app { namespace api { APIOperationPtr Operations::_handler(Request& request) { param_t op = request.getVariable("op"); if (!op) request.on400("Operation is missing"); auto _it = m_handlers.find(op); if (_it == m_handlers.end()) return nullptr; #if DEBUG_CGI return _it->second.ptr; #else return _it->second; #endif } }}} namespace FastCGI { namespace app { namespace reader { class ApiPageHandler: public Handler { public: std::string name() const { return "reedr API"; } void visit(Request& request) { api::APIOperationPtr ptr = api::Operations::handler(request); if (!ptr) request.on400("Operation not recognized"); SessionPtr session = request.getSession(); PageTranslation tr; if (!tr.init(session, request)) request.on500(); ptr->render(session, request, tr); } }; }}} REGISTER_HANDLER("/data/api", FastCGI::app::reader::ApiPageHandler); <commit_msg>Whole API will be JSON-based<commit_after>/* * Copyright (C) 2013 midnightBITS * * 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 "pch.h" #include <handlers.hpp> #include <utils.hpp> #include "api_handler.hpp" #include "json.hpp" namespace FastCGI { namespace app { namespace api { APIOperationPtr Operations::_handler(Request& request) { param_t op = request.getVariable("op"); if (!op) { request.setHeader("Content-Type", "application/json; charset=utf-8"); request.setHeader("Status", "400 Operation is missing"); request << "{\"error\":\"Operation is missing\"}"; request.die(); } auto _it = m_handlers.find(op); if (_it == m_handlers.end()) return nullptr; #if DEBUG_CGI return _it->second.ptr; #else return _it->second; #endif } }}} namespace FastCGI { namespace app { namespace reader { class ApiPageHandler: public Handler { public: std::string name() const { return "reedr API"; } void visit(Request& request) { api::APIOperationPtr ptr = api::Operations::handler(request); if (!ptr) { request.setHeader("Content-Type", "application/json; charset=utf-8"); request.setHeader("Status", "404 Operation not recognized"); request << "{\"error\":\"Operation not recognized\",\"op\":" << json::escape(request.getVariable("op")) << "}"; request.die(); } SessionPtr session = request.getSession(); PageTranslation tr; if (!tr.init(session, request)) request.on500(); ptr->render(session, request, tr); } }; }}} REGISTER_HANDLER("/data/api", FastCGI::app::reader::ApiPageHandler); <|endoftext|>
<commit_before>/** * @file * @brief Inheritance example * @date 28.12.12 * @author Felix Sulima */ #include <framework/example/self.h> #include <new> #include <cstdio> // TEST: include all C++ headers #include <cassert> #include <cctype> #include <cerrno> #include <cmath> #include <csetjmp> #include <cstdarg> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <exception> #include <new> #include <typeinfo> // END TEST EMBOX_EXAMPLE(run); class Base; typedef void (* pbase_fn_t) (Base &base); class Base { public: Base(pbase_fn_t fn) { std::printf(">> [obj %p] Base(%p)\n", this, fn); if (fn) { fn(*this); } } virtual void testPureVirtual(void) = 0; virtual ~Base() = 0; }; Base::~Base() { std::printf(">> [obj %p] ~Base()\n", this); } class Derived : public Base { public: virtual void testPureVirtual(void) { std::printf(">> [obj %p] Derived.testPureVirtual() without any arguments\n", this); } Derived(pbase_fn_t fn) : Base(fn) { std::printf(">> [obj %p] Derived(%p)\n", this, fn); } ~Derived() { std::printf(">> [obj %p] ~Derived()\n", this); } }; static void callPureVirtual(Base& base) { assert(true); base.testPureVirtual(); } static int run(int argc, char **argv) { // stack { std::puts("Derived without any arguments -- on stack"); Derived derived(); } // Null argument { std::puts("Derived with NULL argument -- on stack"); Derived derived(NULL); } // Calling pure virtual function { std::puts("Calling pure virtual function"); Derived derived(callPureVirtual); } return 0; } <commit_msg>tests: cxx: Fix inheritance test<commit_after>/** * @file * @brief Inheritance example * @date 28.12.12 * @author Felix Sulima */ #include <new> #include <cstdio> #include <embox/test.h> #include "test_cxx.h" EMBOX_TEST_SUITE_EXT("c++ inheritance test", NULL, NULL, NULL, NULL); namespace { class Base { public: Base(int val) { test_emit('a'); } virtual void pure_virtual_fn(void) = 0; virtual ~Base() = 0; }; Base::~Base() { test_emit('b'); } class Derived : public Base { public: Derived(int val) : Base(val) {test_emit('c');} ~Derived() { test_emit('d');} void pure_virtual_fn(void) {test_emit('e');} }; TEST_CASE("Inheritance test") { { Derived derived(0); } test_assert_emitted("acdb"); } TEST_CASE("Calling virtual function") { { Derived derived(0); derived.pure_virtual_fn(); } test_assert_emitted("acedb"); } } /* namespace */ <|endoftext|>
<commit_before>// Copyright (c) 2020 Intel Corporation // // 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 "mfx_common.h" #if defined(MFX_ENABLE_H265_VIDEO_ENCODE) && defined(MFX_VA_LINUX) #include "hevcehw_g9_dirty_rect_lin.h" #include "hevcehw_g9_va_packer_lin.h" using namespace HEVCEHW; using namespace HEVCEHW::Gen9; void Linux::Gen9::DirtyRect::InitAlloc(const FeatureBlocks& /*blocks*/, TPushIA Push) { Push(BLK_SetCallChains , [this](StorageRW& global, StorageRW& /*local*/) -> mfxStatus { auto& vaPacker = VAPacker::CC::Get(global); vaPacker.AddPerPicMiscData[VAEncMiscParameterTypeDirtyRect].Push([this]( VAPacker::CallChains::TAddMiscData::TExt , const StorageR& global , const StorageR& s_task , std::list<std::vector<mfxU8>>& data) { auto dirtyRect = GetRTExtBuffer<mfxExtDirtyRect>(global, s_task); mfxU32 log2blkSize = Glob::EncodeCaps::Get(global).BlockSize + 3; auto& vaDirtyRect = AddVaMisc<VAEncMiscParameterBufferDirtyRect>(VAEncMiscParameterTypeDirtyRect, data); vaDirtyRect.num_roi_rectangle = 0; m_vaDirtyRects.clear(); for (int i = 0; i < dirtyRect.NumRect; i++) { if (SkipRectangle(dirtyRect.Rect[i])) continue; /* Driver expects a rect with the 'close' right bottom edge but MSDK uses the 'open' edge rect, thus the right bottom edge which is decreased by 1 below converts 'open' -> 'close' notation We expect here boundaries are already aligned with the BlockSize and Right > Left and Bottom > Top */ m_vaDirtyRects.push_back({ int16_t(dirtyRect.Rect[i].Top) , int16_t(dirtyRect.Rect[i].Left) , uint16_t((dirtyRect.Rect[i].Right - dirtyRect.Rect[i].Left) - (1 << log2blkSize)) , uint16_t((dirtyRect.Rect[i].Bottom - dirtyRect.Rect[i].Top) - (1 << log2blkSize)) }); ++vaDirtyRect.num_roi_rectangle; } vaDirtyRect.roi_rectangle = vaDirtyRect.num_roi_rectangle ? m_vaDirtyRects.data() : nullptr; return vaDirtyRect.num_roi_rectangle ? 1 : 0; }); return MFX_ERR_NONE; }); } #endif //defined(MFX_ENABLE_H265_VIDEO_ENCODE) <commit_msg>[hevce r] Fix dirty rect parameters<commit_after>// Copyright (c) 2020 Intel Corporation // // 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 "mfx_common.h" #if defined(MFX_ENABLE_H265_VIDEO_ENCODE) && defined(MFX_VA_LINUX) #include "hevcehw_g9_dirty_rect_lin.h" #include "hevcehw_g9_va_packer_lin.h" using namespace HEVCEHW; using namespace HEVCEHW::Gen9; void Linux::Gen9::DirtyRect::InitAlloc(const FeatureBlocks& /*blocks*/, TPushIA Push) { Push(BLK_SetCallChains , [this](StorageRW& global, StorageRW& /*local*/) -> mfxStatus { auto& vaPacker = VAPacker::CC::Get(global); vaPacker.AddPerPicMiscData[VAEncMiscParameterTypeDirtyRect].Push([this]( VAPacker::CallChains::TAddMiscData::TExt , const StorageR& global , const StorageR& s_task , std::list<std::vector<mfxU8>>& data) { auto dirtyRect = GetRTExtBuffer<mfxExtDirtyRect>(global, s_task); mfxU32 log2blkSize = Glob::EncodeCaps::Get(global).BlockSize + 3; auto& vaDirtyRect = AddVaMisc<VAEncMiscParameterBufferDirtyRect>(VAEncMiscParameterTypeDirtyRect, data); vaDirtyRect.num_roi_rectangle = 0; m_vaDirtyRects.clear(); for (int i = 0; i < dirtyRect.NumRect; i++) { if (SkipRectangle(dirtyRect.Rect[i])) continue; /* Driver expects a rect with the 'close' right bottom edge but MSDK uses the 'open' edge rect, thus the right bottom edge which is decreased by 1 below converts 'open' -> 'close' notation We expect here boundaries are already aligned with the BlockSize and Right > Left and Bottom > Top */ m_vaDirtyRects.push_back({ int16_t(dirtyRect.Rect[i].Left) , int16_t(dirtyRect.Rect[i].Top) , uint16_t((dirtyRect.Rect[i].Right - dirtyRect.Rect[i].Left) - (1 << log2blkSize)) , uint16_t((dirtyRect.Rect[i].Bottom - dirtyRect.Rect[i].Top) - (1 << log2blkSize)) }); ++vaDirtyRect.num_roi_rectangle; } vaDirtyRect.roi_rectangle = vaDirtyRect.num_roi_rectangle ? m_vaDirtyRects.data() : nullptr; return vaDirtyRect.num_roi_rectangle ? 1 : 0; }); return MFX_ERR_NONE; }); } #endif //defined(MFX_ENABLE_H265_VIDEO_ENCODE) <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: debug.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: as $ $Date: 2001-05-02 13:00:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #define __FRAMEWORK_MACROS_DEBUG_HXX_ //***************************************************************************************************************** // Disable all feature of this file in produkt version! // But enable normal assertion handling (as messagebox) in normal debug version. // User can overwrite these adjustment with his own values! We will do it only if nothing is set. //***************************************************************************************************************** #ifndef DEBUG #undef ENABLE_LOGMECHANISM #undef ENABLE_ASSERTIONS #undef ENABLE_EVENTDEBUG #undef ENABLE_MUTEXDEBUG #undef ENABLE_REGISTRATIONDEBUG #undef ENABLE_TARGETINGDEBUG #undef ENABLE_PLUGINDEBUG #else // Enable log mechanism for assertion handling. #ifndef ENABLE_LOGMECHANISM #define ENABLE_LOGMECHANISM #endif // Enable assertion handling himself. // The default logtype is MESSAGEBOX. // see "assertion.hxx" for further informations #ifndef ENABLE_ASSERTIONS #define ENABLE_ASSERTIONS #endif #ifndef ENABLE_MUTEXDEBUG #define ENABLE_MUTEXDEBUG #endif #endif //***************************************************************************************************************** // generic macros for logging //***************************************************************************************************************** #ifndef __FRAMEWORK_MACROS_DEBUG_LOGMECHANISM_HXX_ #include <macros/debug/logmechanism.hxx> #endif //***************************************************************************************************************** // special macros for assertion handling //***************************************************************************************************************** #ifndef __FRAMEWORK_MACROS_DEBUG_ASSERTION_HXX_ #include <macros/debug/assertion.hxx> #endif //***************************************************************************************************************** // special macros for event handling //***************************************************************************************************************** #ifndef __FRAMEWORK_MACROS_DEBUG_EVENT_HXX_ #include <macros/debug/event.hxx> #endif //***************************************************************************************************************** // special macros to debug mutex handling //***************************************************************************************************************** #ifndef __FRAMEWORK_MACROS_DEBUG_MUTEX_HXX_ #include <macros/debug/mutex.hxx> #endif //***************************************************************************************************************** // special macros to debug service registration //***************************************************************************************************************** #ifndef __FRAMEWORK_MACROS_DEBUG_REGISTRATION_HXX_ #include <macros/debug/registration.hxx> #endif //***************************************************************************************************************** // special macros to debug targeting of frames //***************************************************************************************************************** #ifndef __FRAMEWORK_MACROS_DEBUG_TARGETING_HXX_ #include <macros/debug/targeting.hxx> #endif //***************************************************************************************************************** // special macros to debug our plugin and his asynchronous methods! //***************************************************************************************************************** #ifndef __FRAMEWORK_MACROS_DEBUG_PLUGIN_HXX_ #include <macros/debug/plugin.hxx> #endif //***************************************************************************************************************** // end of file //***************************************************************************************************************** #endif // #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ <commit_msg>enable assertions for non produkt version<commit_after>/************************************************************************* * * $RCSfile: debug.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: as $ $Date: 2001-05-04 13:13:15 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #define __FRAMEWORK_MACROS_DEBUG_HXX_ //***************************************************************************************************************** // Disable all feature of this file in produkt version! // But enable normal assertion handling (as messagebox) in normal debug version. // User can overwrite these adjustment with his own values! We will do it only if nothing is set. //***************************************************************************************************************** #ifndef _DEBUG #undef ENABLE_LOGMECHANISM #undef ENABLE_ASSERTIONS #undef ENABLE_EVENTDEBUG #undef ENABLE_MUTEXDEBUG #undef ENABLE_REGISTRATIONDEBUG #undef ENABLE_TARGETINGDEBUG #undef ENABLE_PLUGINDEBUG #else // Enable log mechanism for assertion handling. #ifndef ENABLE_LOGMECHANISM #define ENABLE_LOGMECHANISM #endif // Enable assertion handling himself. // The default logtype is MESSAGEBOX. // see "assertion.hxx" for further informations #ifndef ENABLE_ASSERTIONS #define ENABLE_ASSERTIONS #endif #ifndef ENABLE_MUTEXDEBUG #define ENABLE_MUTEXDEBUG #endif #endif //***************************************************************************************************************** // generic macros for logging //***************************************************************************************************************** #ifndef __FRAMEWORK_MACROS_DEBUG_LOGMECHANISM_HXX_ #include <macros/debug/logmechanism.hxx> #endif //***************************************************************************************************************** // special macros for assertion handling //***************************************************************************************************************** #ifndef __FRAMEWORK_MACROS_DEBUG_ASSERTION_HXX_ #include <macros/debug/assertion.hxx> #endif //***************************************************************************************************************** // special macros for event handling //***************************************************************************************************************** #ifndef __FRAMEWORK_MACROS_DEBUG_EVENT_HXX_ #include <macros/debug/event.hxx> #endif //***************************************************************************************************************** // special macros to debug mutex handling //***************************************************************************************************************** #ifndef __FRAMEWORK_MACROS_DEBUG_MUTEX_HXX_ #include <macros/debug/mutex.hxx> #endif //***************************************************************************************************************** // special macros to debug service registration //***************************************************************************************************************** #ifndef __FRAMEWORK_MACROS_DEBUG_REGISTRATION_HXX_ #include <macros/debug/registration.hxx> #endif //***************************************************************************************************************** // special macros to debug targeting of frames //***************************************************************************************************************** #ifndef __FRAMEWORK_MACROS_DEBUG_TARGETING_HXX_ #include <macros/debug/targeting.hxx> #endif //***************************************************************************************************************** // special macros to debug our plugin and his asynchronous methods! //***************************************************************************************************************** #ifndef __FRAMEWORK_MACROS_DEBUG_PLUGIN_HXX_ #include <macros/debug/plugin.hxx> #endif //***************************************************************************************************************** // end of file //***************************************************************************************************************** #endif // #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ <|endoftext|>
<commit_before>#include <cmath> #include <cstdio> #include <omp.h> // (Sub-optimum) Array of Structure - good OOP. Bad Performance. // Structure of individual particle //struct ParticleType { // float x, y, z; // float vx, vy, vz; //}; // (Optimum) Structure of Array - bad OOP. Good performance. struct ParticleSetType { float *x, *y, *z; float *vx, *vy, *vz; }; //ย define a function that moves each particle due to interaction with other particles void MoveParticles(const int nParticles, ParticleSetType & particle, const float dt) { const int TILE = 16; #pragma omp parallel for // Loop over particles that experience force for (int ii = 0; ii < nParticles; ii+=TILE) { // Components of the gravity force on particle i float Fx[TILE], Fy[TILE], Fz[TILE]; Fx[0:TILE] = Fy[0:TILE] = Fz[0:TILE] = 0.0f; // Loop over particles that exert force: vectorization expected here #pragma unroll(TILE) for (int j = 0; j < nParticles; j++) { #pragma vector aligned // How much data in this tiled loop? // 16 (particles in a tile) * 3 floats * 4 bytes per floats = 192 bytes // enough to fit in the L1 Cache registery for (int i = ii; i < ii+TILE; i++) { // Avoid singularity and interaction with self const float softening = 1e-20; // Newton's law of universal gravity const float dx = particle.x[j] - particle.x[i]; const float dy = particle.y[j] - particle.y[i]; const float dz = particle.z[j] - particle.z[i]; const float drSquared = dx*dx + dy*dy + dz*dz + softening; const float oodr = 1.0f/sqrtf(drSquared); const float drPowerN3 = oodr*oodr*oodr; // Calculate the net force // Assume mass is 1 (for ease of computation) // F = ma = 1*a = a Fx[i-ii] += dx * oodr; // scalar tuning Fy[i-ii] += dy * oodr; // scalar tuning Fz[i-ii] += dz * oodr; // scalar tuning } } // Accelerate particles in response to the gravitational force // Note: 1st order Euler Approximation. // http://spiff.rit.edu/classes/phys317/lectures/euler.html particle.vx[ii:TILE] += dt*Fx[0:TILE]; particle.vy[ii:TILE] += dt*Fy[0:TILE]; particle.vz[ii:TILE] += dt*Fz[0:TILE]; } #pragma omp parallel for // Move particles according to their velocities for (int i = 0 ; i < nParticles; i++) { particle.x[i] += particle.vx[i]*dt; particle.y[i] += particle.vy[i]*dt; particle.z[i] += particle.vz[i]*dt; } } // Do it! int main(const int argc, const char *argv[]) { // Problem size and other parameters const int nParticles = (argc > 1 ? atoi(argv[1]) : 16384); const int nSteps = 10; // Duration of test const float dt = 0.01f; // Particle propagation time step // Particle data stored as an Array of Structures (AoS) // this is good object-oriented programming style, // but inefficient for the purposes of vectorization //ParticleType *particle = new ParticleType[nParticles]; // Structure of Array (SoA) style // bad OOP style. But very efficient in terms of performance. ParticleSetType particle; // use Intel _mm_malloc to create objects that are stored on aligned memory. // For KNL, needs to align to start at multiple of 64 bytes. // use _mm_free to deallocate particle.x = (float*) _mm_malloc(sizeof(float)*nParticles, 64); particle.y = (float*) _mm_malloc(sizeof(float)*nParticles, 64);; particle.z = (float*) _mm_malloc(sizeof(float)*nParticles, 64);; particle.vx = (float*) _mm_malloc(sizeof(float)*nParticles, 64);; particle.vy = (float*) _mm_malloc(sizeof(float)*nParticles, 64);; particle.vz = (float*) _mm_malloc(sizeof(float)*nParticles, 64);; // Initialize random number generator and particles srand(0); for(int i = 0; i < nParticles; i++) { particle.x[i] = rand()/RAND_MAX; particle.y[i] = rand()/RAND_MAX; particle.z[i] = rand()/RAND_MAX; particle.vx[i] = rand()/RAND_MAX; particle.vy[i] = rand()/RAND_MAX; particle.vz[i] = rand()/RAND_MAX; } // Perform benchmark const int version = 10; // implementation version - update as needed printf("\n\033[1mNBODY Version %d\033[0m\n", version); const int num_threads = omp_get_max_threads(); printf("\nPropagating %d particles using %d threads on %s...\n\n", nParticles, num_threads, #ifndef __MIC__ "CPU" #else "MIC" #endif ); // Benchmarking data // rate and duration are for computing overall average performance and duration // dRate and dDuration are for computing the short-cut standard diviation later. double rate = 0, dRate = 0, duration = 0, dDuration = 0; // Skip first few steps in the computation of average performance. Likely warm-up on Xeon Phi processor const int skipSteps = 3; printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s"); fflush(stdout); for (int step = 1; step <= nSteps; step++) { const double tStart = omp_get_wtime(); // Start timing MoveParticles(nParticles, particle, dt); const double tEnd = omp_get_wtime(); // End timing // Estimate total interactions and GFLOPS consumed const float HztoInts = float(nParticles)*float(nParticles-1) ; const float HztoGFLOPs = 20.0*1e-9*float(nParticles)*float(nParticles-1); // For average performance and short-cut method standard deviation computation if (step > skipSteps) { // Collect statistics rate += HztoGFLOPs/(tEnd - tStart); dRate += HztoGFLOPs*HztoGFLOPs/((tEnd - tStart)*(tEnd-tStart)); duration += (tEnd - tStart); dDuration += (tEnd - tStart)*(tEnd - tStart); } printf("%5d %10.3e %10.3e %8.1f %s\n", step, (tEnd-tStart), HztoInts/(tEnd-tStart), HztoGFLOPs/(tEnd-tStart), (step<=skipSteps?"*":"")); fflush(stdout); } // Compute the short-cut method standard deviaion. rate/=(double)(nSteps-skipSteps); dRate=sqrt(dRate/(double)(nSteps-skipSteps)-rate*rate); duration/=(double)(nSteps-skipSteps); dDuration=sqrt(dDuration/(double)(nSteps-skipSteps)-duration*duration); printf("-----------------------------------------------------\n"); printf("\033[1m%s %4s \033[42m%10.1f +- %.1f GFLOP/s\033[0m\n", "Average performance:", "", rate, dRate); printf("\033[1m%s %4s \033[42m%10.3e +- %10.3e s\033[0m\n", "Average duration:", "", duration, dDuration); printf("\033[1m%s %4s \033[42m%.3f +- %.3f ms\033[0m\n", "Average duration:", "", duration*1000.0, dDuration*1000.0); printf("-----------------------------------------------------\n"); printf("* - warm-up, not included in average\n\n"); // free memory _mm_free(particle.x); _mm_free(particle.y); _mm_free(particle.z); _mm_free(particle.vx); _mm_free(particle.vy); _mm_free(particle.vz); } <commit_msg>Update nbody.cc<commit_after>#include <cmath> #include <cstdio> #include <omp.h> // (Sub-optimum) Array of Structure - good OOP. Bad Performance. // Structure of individual particle //struct ParticleType { // float x, y, z; // float vx, vy, vz; //}; // (Optimum) Structure of Array - bad OOP. Good performance. struct ParticleSetType { float *x, *y, *z; float *vx, *vy, *vz; }; //ย define a function that moves each particle due to interaction with other particles void MoveParticles(const int nParticles, ParticleSetType & particle, const float dt) { const int TILE = 16; #pragma omp parallel for // Loop over particles that experience force for (int ii = 0; ii < nParticles; ii+=TILE) { // Components of the gravity force on particle i float Fx[TILE], Fy[TILE], Fz[TILE]; Fx[0:TILE] = Fy[0:TILE] = Fz[0:TILE] = 0.0f; // Loop over particles that exert force: vectorization expected here #pragma unroll(TILE) for (int j = 0; j < nParticles; j++) { #pragma vector aligned // How much data in this tiled loop? // 16 (particles in a tile) * 3 floats * 4 bytes per floats = 192 bytes // enough to fit in the L1 Cache registery for (int i = ii; i < ii+TILE; i++) { // Avoid singularity and interaction with self const float softening = 1e-20; // Newton's law of universal gravity const float dx = particle.x[j] - particle.x[i]; const float dy = particle.y[j] - particle.y[i]; const float dz = particle.z[j] - particle.z[i]; const float drSquared = dx*dx + dy*dy + dz*dz + softening; const float oodr = 1.0f/sqrtf(drSquared); const float drPowerN3 = oodr*oodr*oodr; // Calculate the net force // Assume mass is 1 (for ease of computation) // F = ma = 1*a = a Fx[i-ii] += dx * drPowerN3; // scalar tuning Fy[i-ii] += dy * drPowerN3; // scalar tuning Fz[i-ii] += dz * drPowerN3; // scalar tuning } } // Accelerate particles in response to the gravitational force // Note: 1st order Euler Approximation. // http://spiff.rit.edu/classes/phys317/lectures/euler.html particle.vx[ii:TILE] += dt*Fx[0:TILE]; particle.vy[ii:TILE] += dt*Fy[0:TILE]; particle.vz[ii:TILE] += dt*Fz[0:TILE]; } #pragma omp parallel for // Move particles according to their velocities for (int i = 0 ; i < nParticles; i++) { particle.x[i] += particle.vx[i]*dt; particle.y[i] += particle.vy[i]*dt; particle.z[i] += particle.vz[i]*dt; } } // Do it! int main(const int argc, const char *argv[]) { // Problem size and other parameters const int nParticles = (argc > 1 ? atoi(argv[1]) : 16384); const int nSteps = 10; // Duration of test const float dt = 0.01f; // Particle propagation time step // Particle data stored as an Array of Structures (AoS) // this is good object-oriented programming style, // but inefficient for the purposes of vectorization //ParticleType *particle = new ParticleType[nParticles]; // Structure of Array (SoA) style // bad OOP style. But very efficient in terms of performance. ParticleSetType particle; // use Intel _mm_malloc to create objects that are stored on aligned memory. // For KNL, needs to align to start at multiple of 64 bytes. // use _mm_free to deallocate particle.x = (float*) _mm_malloc(sizeof(float)*nParticles, 64); particle.y = (float*) _mm_malloc(sizeof(float)*nParticles, 64);; particle.z = (float*) _mm_malloc(sizeof(float)*nParticles, 64);; particle.vx = (float*) _mm_malloc(sizeof(float)*nParticles, 64);; particle.vy = (float*) _mm_malloc(sizeof(float)*nParticles, 64);; particle.vz = (float*) _mm_malloc(sizeof(float)*nParticles, 64);; // Initialize random number generator and particles srand(0); for(int i = 0; i < nParticles; i++) { particle.x[i] = rand()/RAND_MAX; particle.y[i] = rand()/RAND_MAX; particle.z[i] = rand()/RAND_MAX; particle.vx[i] = rand()/RAND_MAX; particle.vy[i] = rand()/RAND_MAX; particle.vz[i] = rand()/RAND_MAX; } // Perform benchmark const int version = 10; // implementation version - update as needed printf("\n\033[1mNBODY Version %d\033[0m\n", version); const int num_threads = omp_get_max_threads(); printf("\nPropagating %d particles using %d threads on %s...\n\n", nParticles, num_threads, #ifndef __MIC__ "CPU" #else "MIC" #endif ); // Benchmarking data // rate and duration are for computing overall average performance and duration // dRate and dDuration are for computing the short-cut standard diviation later. double rate = 0, dRate = 0, duration = 0, dDuration = 0; // Skip first few steps in the computation of average performance. Likely warm-up on Xeon Phi processor const int skipSteps = 3; printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s"); fflush(stdout); for (int step = 1; step <= nSteps; step++) { const double tStart = omp_get_wtime(); // Start timing MoveParticles(nParticles, particle, dt); const double tEnd = omp_get_wtime(); // End timing // Estimate total interactions and GFLOPS consumed const float HztoInts = float(nParticles)*float(nParticles-1) ; const float HztoGFLOPs = 20.0*1e-9*float(nParticles)*float(nParticles-1); // For average performance and short-cut method standard deviation computation if (step > skipSteps) { // Collect statistics rate += HztoGFLOPs/(tEnd - tStart); dRate += HztoGFLOPs*HztoGFLOPs/((tEnd - tStart)*(tEnd-tStart)); duration += (tEnd - tStart); dDuration += (tEnd - tStart)*(tEnd - tStart); } printf("%5d %10.3e %10.3e %8.1f %s\n", step, (tEnd-tStart), HztoInts/(tEnd-tStart), HztoGFLOPs/(tEnd-tStart), (step<=skipSteps?"*":"")); fflush(stdout); } // Compute the short-cut method standard deviaion. rate/=(double)(nSteps-skipSteps); dRate=sqrt(dRate/(double)(nSteps-skipSteps)-rate*rate); duration/=(double)(nSteps-skipSteps); dDuration=sqrt(dDuration/(double)(nSteps-skipSteps)-duration*duration); printf("-----------------------------------------------------\n"); printf("\033[1m%s %4s \033[42m%10.1f +- %.1f GFLOP/s\033[0m\n", "Average performance:", "", rate, dRate); printf("\033[1m%s %4s \033[42m%10.3e +- %10.3e s\033[0m\n", "Average duration:", "", duration, dDuration); printf("\033[1m%s %4s \033[42m%.3f +- %.3f ms\033[0m\n", "Average duration:", "", duration*1000.0, dDuration*1000.0); printf("-----------------------------------------------------\n"); printf("* - warm-up, not included in average\n\n"); // free memory _mm_free(particle.x); _mm_free(particle.y); _mm_free(particle.z); _mm_free(particle.vx); _mm_free(particle.vy); _mm_free(particle.vz); } <|endoftext|>
<commit_before> #ifndef MANAGER_HPP_ #define MANAGER_HPP_ #include <vector> #include <map> #include <random> #include "Chromosome.hpp" #define MINIMUM_NUMBER 0 template <class T> class Manager { protected: unsigned int population_size; unsigned int chromosome_size; unsigned int max_generation_number; T max_chromosome_value; T min_chromosome_value; bool use_self_adaptive; double mutation_rate; double mutation_change_rate; double similarity_index; double clonning_rate; double crossover_rate; std::vector<Chromosome<T > > population; // Need to have some way of ensure no duplication of solutions std::vector<Chromosome<T > > solutions; std::mt19937 rand_engine; std::uniform_real_distribution<> op_dist; std::uniform_real_distribution<> chrom_dist; public: /** * Create a manager for GA. * @param population_size The size of population. * @param chromosome_size The size of each chromosome. * @param max_chromosome_value The maximum possible value for the chromosome. * @param min_chromosome_value The minimum possible value for the chromosome. * @param use_self_adaptive Whether to use a self adaptive approach. If this is true * then the mutation rate will be updated based on the similarity of the population. * @param mutation_rate The mutation rate that is used. This is the likelihood that the * mutation operation is applied. If the self adaptive approach is used then this is * the initial mutation rate. * @param mutation_change_rate The rate by which the mutation rate will be updated. * If use_self_adaptive is set to false then this parameter is ignored. * @param similarity_index The threshold at which the similarity mutation rate is * updated. * @param crossover_rate The crossover rate, the likelihood that a chromosome * has the crossover operation applied to it. * @param clonning_rate The clonning rate, the likelihood that a cromosome will be * cloned into the new population. */ Manager(unsigned int population_size, unsigned int chromosome_size, unsigned int max_generations_number, T max_chromosome_value, T min_chromosome_value, bool use_self_adaptive, double mutation_rate, double mutation_change_rate, double similarity_index, double crossover_rate, double clonning_rate) : population_size(population_size), chromosome_size(chromosome_size), max_generation_number(max_generation_number), max_chromosome_value(max_chromosome_value), min_chromosome_value(min_chromosome_value), use_self_adaptive(use_self_adaptive), mutation_rate(mutation_rate), mutation_change_rate(mutation_change_rate), similarity_index(similarity_index), clonning_rate(clonning_rate), crossover_rate(crossover_rate), population(population_size) { initialize(); } /** * Create a non self-adaptive GA manager * @param population_size The size of population. * @param chromosome_size The size of each chromosome. * @param max_chromosome_value The maximum possible value for the chromosome. * @param min_chromosome_value The minimum possible value for the chromosome. * @param mutation_rate The mutation rate that is used. This is the likelihood that the * mutation operation is applied. If the self adaptive approach is used then this is * the initial mutation rate. * @param crossover_rate The crossover rate, the likelihood that a chromosome * has the crossover operation applied to it. * @param clonning_rate The clonning rate, the likelihood that a cromosome will be * cloned into the new population. */ Manager(unsigned int population_size, unsigned int chromosome_size, unsigned int max_generation_number, T max_chromosome_value, T min_chromosome_value, double mutation_rate, double crossover_rate, double clonning_rate) : population_size(population_size), chromosome_size(chromosome_size), max_generation_number(max_generation_number), max_chromosome_value(max_chromosome_value), min_chromosome_value(min_chromosome_value), use_self_adaptive(false), mutation_rate(mutation_rate), mutation_change_rate(0), similarity_index(0), clonning_rate(clonning_rate), crossover_rate(crossover_rate), population(population_size) { initialize(); } /** * Run the algorithm for the specificed number of generations */ void run() { for(unsigned int i = 0; i < max_generation_number; i++) { runGeneration(); } } /** * Apply the fitness function to the population. Given the result of the * fitness function, the next population is bread. */ void runGeneration() { // Fitness function would be a generic method passed as an argument that is apply to each chromosome // Given that threads are going to be used: // - Create a thread pool and attempt to assign a reduced set of chromosomes to each thread // - Since each chromosome is independent for the execution of the fitness function they can be 1 thread per chromosome (hypothedically) // Given that MPI is being used // - Reduce the chromosomes into smaller sets and assign them to a node // - Each node can then divide the subpopulation further (possibly to a per-chromosome per thread) depending on availablity. (this step is similar to the second step with threading. // Apply the fitness function // Could potentially have a second generic method that you could use to apply heuristics to a found solution. // eg; in N-Queens you can rotate the board in order to find more solutions. // Can be done concurrently with the fitness function if(use_self_adaptive) { selfAdapt(); } // Main thread will wait for all children to finish executing before proceeding. // Construct the list of results for the fitness function in a map which maps the chromosome's index to the chromosome's fitness value. The type of the result of the fitness function can be any desired type however primitive is desired. eg: std::map<unsigned int, int > fitness_results; breed(fitness_results); } /** * Prepare the population for the next generation by apply the genetic operations. */ template <typename F> void breed(std::map<unsigned int, F > fitness_result) { std::vector<Chromosome<T > > new_population; // Iterate through the chromosomes while(new_population.size() < population_size) { // TODO Using a specific selection (eg roulette wheel without replacement) to pick a chromosome // Use a random number between to identify which operation to apply (each operation gets a slice of the range) int selected_operation = 0; int selected_chromosome = getRandChromosome(); if(selected_operation == 0) { // Mutation population[selected_chromosome].mutation(new_population); } else if(selected_operation == 1) { // Crossover // Pick another chromosome from the population that is not the already selected chromosome. (TODO can the chromosome be the same as the initally selected on?) int other_selected_chromosome = getRandChromosome(selected_chromosome); population[selected_chromosome].crossover(population[other_selected_chromosome], new_population); } else { // Clone population[selected_chromosome].clone(new_population); } } // Update the population to the new population population = new_population; // Check if this creates a shallow copy (since we aren't going to change new_population so we just want it to be deallocated at the end of the method). } /** * Apply the self-adaptive operation to determine the similarity of the chromosomes * and update the mutation rate accordingly. */ void selfAdapt() { // Determine how similar the chromosome is to the rest of the population // Sequencial solution // Iterate through the chromosomes // Calculate the current chromosome with each of the others in the population // Based on the similarity of the population identify adjust the mutaiton rate //if the similarity is too high (above threshold), increase mutation rate //if similarity is too low (below threshold), decrease mutation rate //otherwise (same as threshold), do nothing } // Instead of taking a fitness function it might be better to take a function pointer and call that function for the fitness function // void *fitness_function(std::vector<Chromosome<T > > population); /*static void *fitness_function(std::vector<Chromosome<T > > population) { return NULL; }*/ private: void initialize() { // Create the random objects that will be used std::random_device rd; rand_engine = std::mt19937 (rd()); op_dist = std::uniform_real_distribution<> (0, 100); chrom_dist = std::uniform_real_distribution<> (MINIMUM_NUMBER, population_size-1); Chromosome<T >::initialize(chromosome_size, min_chromosome_value, max_chromosome_value); } /** * Get a number between 0 and population.size() - 1 * @return A number between 0 and population.size()-1 */ unsigned int getRandChromosome() { return chrom_dist(rand_engine); } /** * Get a random number between 0 and population.size()-1 that is not index * @param index The only value within the range that the return cannot be. * @return A number within the defined range that is not index. */ unsigned int getRandChromosome(unsigned int index) { unsigned int val = getRandChromosome(); while(val == index) { val = getRandChromosome(); } return val; } }; #endif /* MANAGER_HPP_ */ <commit_msg>ADDED: function pointer reference<commit_after> #ifndef MANAGER_HPP_ #define MANAGER_HPP_ #include <vector> #include <map> #include <random> #include "Chromosome.hpp" #define MINIMUM_NUMBER 0 template <class T> class Manager { protected: unsigned int population_size; unsigned int chromosome_size; unsigned int max_generation_number; T max_chromosome_value; T min_chromosome_value; bool use_self_adaptive; double mutation_rate; double mutation_change_rate; double similarity_index; double clonning_rate; double crossover_rate; std::vector<Chromosome<T > > population; // Need to have some way of ensure no duplication of solutions std::vector<Chromosome<T > > solutions; std::mt19937 rand_engine; std::uniform_real_distribution<> op_dist; std::uniform_real_distribution<> chrom_dist; public: /** * Create a manager for GA. * @param population_size The size of population. * @param chromosome_size The size of each chromosome. * @param max_chromosome_value The maximum possible value for the chromosome. * @param min_chromosome_value The minimum possible value for the chromosome. * @param use_self_adaptive Whether to use a self adaptive approach. If this is true * then the mutation rate will be updated based on the similarity of the population. * @param mutation_rate The mutation rate that is used. This is the likelihood that the * mutation operation is applied. If the self adaptive approach is used then this is * the initial mutation rate. * @param mutation_change_rate The rate by which the mutation rate will be updated. * If use_self_adaptive is set to false then this parameter is ignored. * @param similarity_index The threshold at which the similarity mutation rate is * updated. * @param crossover_rate The crossover rate, the likelihood that a chromosome * has the crossover operation applied to it. * @param clonning_rate The clonning rate, the likelihood that a cromosome will be * cloned into the new population. */ Manager(unsigned int population_size, unsigned int chromosome_size, unsigned int max_generations_number, T max_chromosome_value, T min_chromosome_value, bool use_self_adaptive, double mutation_rate, double mutation_change_rate, double similarity_index, double crossover_rate, double clonning_rate) : population_size(population_size), chromosome_size(chromosome_size), max_generation_number(max_generation_number), max_chromosome_value(max_chromosome_value), min_chromosome_value(min_chromosome_value), use_self_adaptive(use_self_adaptive), mutation_rate(mutation_rate), mutation_change_rate(mutation_change_rate), similarity_index(similarity_index), clonning_rate(clonning_rate), crossover_rate(crossover_rate), population(population_size) { initialize(); } /** * Create a non self-adaptive GA manager * @param population_size The size of population. * @param chromosome_size The size of each chromosome. * @param max_chromosome_value The maximum possible value for the chromosome. * @param min_chromosome_value The minimum possible value for the chromosome. * @param mutation_rate The mutation rate that is used. This is the likelihood that the * mutation operation is applied. If the self adaptive approach is used then this is * the initial mutation rate. * @param crossover_rate The crossover rate, the likelihood that a chromosome * has the crossover operation applied to it. * @param clonning_rate The clonning rate, the likelihood that a cromosome will be * cloned into the new population. */ Manager(unsigned int population_size, unsigned int chromosome_size, unsigned int max_generation_number, T max_chromosome_value, T min_chromosome_value, double mutation_rate, double crossover_rate, double clonning_rate) : population_size(population_size), chromosome_size(chromosome_size), max_generation_number(max_generation_number), max_chromosome_value(max_chromosome_value), min_chromosome_value(min_chromosome_value), use_self_adaptive(false), mutation_rate(mutation_rate), mutation_change_rate(0), similarity_index(0), clonning_rate(clonning_rate), crossover_rate(crossover_rate), population(population_size) { initialize(); } /** * Run the algorithm for the specificed number of generations */ void run(void (* fptr)(void*)) { for(unsigned int i = 0; i < max_generation_number; i++) { runGeneration(&fptr); } } /** * Apply the fitness function to the population. Given the result of the * fitness function, the next population is bread. */ void runGeneration(void (* fptr)(void*)) { // Fitness function would be a generic method passed as an argument that is apply to each chromosome fptr(population); // Given that threads are going to be used: // - Create a thread pool and attempt to assign a reduced set of chromosomes to each thread // - Since each chromosome is independent for the execution of the fitness function they can be 1 thread per chromosome (hypothedically) // Given that MPI is being used // - Reduce the chromosomes into smaller sets and assign them to a node // - Each node can then divide the subpopulation further (possibly to a per-chromosome per thread) depending on availablity. (this step is similar to the second step with threading. // Apply the fitness function // Could potentially have a second generic method that you could use to apply heuristics to a found solution. // eg; in N-Queens you can rotate the board in order to find more solutions. // Can be done concurrently with the fitness function if(use_self_adaptive) { selfAdapt(); } // Main thread will wait for all children to finish executing before proceeding. // Construct the list of results for the fitness function in a map which maps the chromosome's index to the chromosome's fitness value. The type of the result of the fitness function can be any desired type however primitive is desired. eg: std::map<unsigned int, int > fitness_results; breed(fitness_results); } /** * Prepare the population for the next generation by apply the genetic operations. */ template <typename F> void breed(std::map<unsigned int, F > fitness_result) { std::vector<Chromosome<T > > new_population; // Iterate through the chromosomes while(new_population.size() < population_size) { // TODO Using a specific selection (eg roulette wheel without replacement) to pick a chromosome // Use a random number between to identify which operation to apply (each operation gets a slice of the range) int selected_operation = 0; int selected_chromosome = getRandChromosome(); if(selected_operation == 0) { // Mutation population[selected_chromosome].mutation(new_population); } else if(selected_operation == 1) { // Crossover // Pick another chromosome from the population that is not the already selected chromosome. (TODO can the chromosome be the same as the initally selected on?) int other_selected_chromosome = getRandChromosome(selected_chromosome); population[selected_chromosome].crossover(population[other_selected_chromosome], new_population); } else { // Clone population[selected_chromosome].clone(new_population); } } // Update the population to the new population population = new_population; // Check if this creates a shallow copy (since we aren't going to change new_population so we just want it to be deallocated at the end of the method). } /** * Apply the self-adaptive operation to determine the similarity of the chromosomes * and update the mutation rate accordingly. */ void selfAdapt() { // Determine how similar the chromosome is to the rest of the population // Sequencial solution // Iterate through the chromosomes // Calculate the current chromosome with each of the others in the population // Based on the similarity of the population identify adjust the mutaiton rate //if the similarity is too high (above threshold), increase mutation rate //if similarity is too low (below threshold), decrease mutation rate //otherwise (same as threshold), do nothing } // Instead of taking a fitness function it might be better to take a function pointer and call that function for the fitness function // void *fitness_function(std::vector<Chromosome<T > > population); /*static void *fitness_function(std::vector<Chromosome<T > > population) { return NULL; }*/ private: void initialize() { // Create the random objects that will be used std::random_device rd; rand_engine = std::mt19937 (rd()); op_dist = std::uniform_real_distribution<> (0, 100); chrom_dist = std::uniform_real_distribution<> (MINIMUM_NUMBER, population_size-1); Chromosome<T >::initialize(chromosome_size, min_chromosome_value, max_chromosome_value); } /** * Get a number between 0 and population.size() - 1 * @return A number between 0 and population.size()-1 */ unsigned int getRandChromosome() { return chrom_dist(rand_engine); } /** * Get a random number between 0 and population.size()-1 that is not index * @param index The only value within the range that the return cannot be. * @return A number within the defined range that is not index. */ unsigned int getRandChromosome(unsigned int index) { unsigned int val = getRandChromosome(); while(val == index) { val = getRandChromosome(); } return val; } }; #endif /* MANAGER_HPP_ */ <|endoftext|>
<commit_before>// // simrecomb.cpp // // Copyright 2012 Darren Kessner // // 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 "Population.hpp" #include <iostream> #include <cstring> #include <fstream> #include <sstream> #include <map> #include "boost/filesystem.hpp" #include "boost/filesystem/fstream.hpp" using namespace std; using boost::shared_ptr; namespace bfs = boost::filesystem; struct SimulationConfig { unsigned int seed; vector<string> geneticMapFilenames; vector< vector<Population::Config> > populationConfigs; // each generation is a vector<Population::Config> SimulationConfig() : seed(0) {} }; ostream& operator<<(ostream& os, const SimulationConfig& simulationConfig) { os << "seed " << simulationConfig.seed << endl << endl; os << "geneticMapFilenames " << simulationConfig.geneticMapFilenames.size() << endl; for (vector<string>::const_iterator it=simulationConfig.geneticMapFilenames.begin(); it!=simulationConfig.geneticMapFilenames.end(); ++it) os << "geneticMapFilename " << *it << endl; os << endl; for (size_t i=0; i<simulationConfig.populationConfigs.size(); i++) { os << "generation " << i << endl; copy(simulationConfig.populationConfigs[i].begin(), simulationConfig.populationConfigs[i].end(), ostream_iterator<Population::Config>(os,"\n")); os << endl; } return os; } istream& operator>>(istream& is, SimulationConfig& simulationConfig) { while (is) { // parse line by line string buffer; getline(is, buffer); if (!is) return is; vector<string> tokens; istringstream iss(buffer); copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(tokens)); // switch on first token if (tokens.empty()) continue; else if (tokens[0] == "seed" && tokens.size() == 2) simulationConfig.seed = atoi(tokens[1].c_str()); else if (tokens[0] == "geneticMapFilenames") continue; else if (tokens[0] == "geneticMapFilename" && tokens.size()==2) simulationConfig.geneticMapFilenames.push_back(tokens[1]); else if (tokens[0] == "generation") simulationConfig.populationConfigs.push_back(vector<Population::Config>()); else if (tokens[0] == "population") { simulationConfig.populationConfigs.back().push_back(Population::Config()); istringstream temp(buffer); temp >> simulationConfig.populationConfigs.back().back(); } else cerr << "Ignoring invalid configuration line:\n" << buffer << endl; } return is; } struct Config { bfs::path configFilename; bfs::path outputDirectory; SimulationConfig simulationConfig; }; void printPopulations(ostream& os, const Populations& populations, const string& label) { os << "<" << label << ">\n"; for (size_t i=0; i<populations.size(); i++) { os << "<population" << i << ">\n" << *populations[i] << "</population" << i << ">\n"; } os << "</" << label << ">\n"; } void initializeDefaultSimulationConfig(SimulationConfig& simulationConfig) { const size_t chromosomePairCount_ = 3; const unsigned int populationSize_ = 10000; const double admixtureProportion_ = .8; // fraction of genes from 1st population for (size_t i=0; i<chromosomePairCount_; i++) simulationConfig.geneticMapFilenames.push_back("genetic_map_chr21_b36.txt"); // hack // generation 0 (ancestral populations) simulationConfig.populationConfigs.push_back(vector<Population::Config>(3)); Population::Config* config = &simulationConfig.populationConfigs[0][0]; config->size = 0; config->populationID = 0; config = &simulationConfig.populationConfigs[0][1]; config->size = populationSize_; config->populationID = 1; config->chromosomePairCount = chromosomePairCount_; config = &simulationConfig.populationConfigs[0][2]; config->size = populationSize_; config->populationID = 2; config->chromosomePairCount = chromosomePairCount_; // generation 1 (initial admixture) simulationConfig.populationConfigs.push_back(vector<Population::Config>(1)); config = &simulationConfig.populationConfigs[1][0]; config->size = populationSize_; double p = admixtureProportion_; config->matingDistribution.push_back(p*p, make_pair(1,1)); config->matingDistribution.push_back(2*p*(1-p), make_pair(1,2)); config->matingDistribution.push_back((1-p)*(1-p), make_pair(2,2)); // subsequent generations - just recombination for (size_t generation=2; generation<8; generation++) { simulationConfig.populationConfigs.push_back(vector<Population::Config>(1)); config = &simulationConfig.populationConfigs[generation][0]; config->size = populationSize_; config->matingDistribution.push_back(1, make_pair(0,0)); } } void initializeRecombinationMaps(const Config& config, const Random& random) { Organism::recombinationPositionGenerator_ = shared_ptr<RecombinationPositionGenerator>( new RecombinationPositionGenerator_RecombinationMap(config.simulationConfig.geneticMapFilenames, random)); } shared_ptr<Populations> createPopulations(shared_ptr<Populations> current, const vector<Population::Config>& populationConfigs, const Random& random) { shared_ptr<Populations> result(new Populations); for (vector<Population::Config>::const_iterator it=populationConfigs.begin(); it!=populationConfigs.end(); ++it) { if (!current.get()) result->push_back(shared_ptr<Population>(new Population(*it))); else result->push_back(shared_ptr<Population>(new Population(*it, *current, random))); } return result; } void simulate(const Config& config) { bfs::ofstream osSimulationConfig(config.outputDirectory / "simrecomb_config.txt"); osSimulationConfig << config.simulationConfig; osSimulationConfig.close(); Random random(config.simulationConfig.seed); cout << "Initializing recombination maps.\n"; initializeRecombinationMaps(config, random); bfs::ofstream osLog(config.outputDirectory / "log.txt"); shared_ptr<Populations> current; for (size_t generation=0; generation<config.simulationConfig.populationConfigs.size(); generation++) { cout << "Generation " << generation << endl; shared_ptr<Populations> next = createPopulations(current, config.simulationConfig.populationConfigs[generation], random); current = next; ostringstream label; label << "gen" << generation; //printPopulations(osLog, *current, label.str()); osLog << generation << endl; } osLog.close(); // output the last generation for (size_t i=0; i<current->size(); ++i) { ostringstream filename; filename << "pop" << i << ".txt"; bfs::ofstream os_pop(config.outputDirectory / filename.str()); os_pop << *(*current)[i]; } } Config parseCommandLine(int argc, char* argv[]) { if (argc==2 && !strcmp(argv[1],"default")) { SimulationConfig temp; initializeDefaultSimulationConfig(temp); cout << temp; exit(0); } if (argc != 3) { cout << "Usage: simrecomb <config_filename> <outputdir>\n"; cout << " or: simrecomb default (prints default config to stdout)\n"; cout << "\n"; cout << "Darren Kessner\n"; cout << "John Novembre Lab, UCLA\n"; throw runtime_error(""); } Config config; config.configFilename = argv[1]; config.outputDirectory = argv[2]; if (!bfs::exists(config.configFilename)) { ostringstream oss; oss << "Config file not found: " << config.configFilename; throw runtime_error(oss.str()); } if (bfs::exists(config.outputDirectory)) { ostringstream oss; oss << "File/directory already exists: " << config.outputDirectory; throw runtime_error(oss.str()); } cout << "Reading configuration file " << config.configFilename << endl; bfs::ifstream is(config.configFilename); is >> config.simulationConfig; is.close(); bfs::create_directories(config.outputDirectory); return config; } int main(int argc, char* argv[]) { try { Config config = parseCommandLine(argc, argv); simulate(config); return 0; } catch(exception& e) { cerr << e.what() << endl; return 1; } catch(...) { cerr << "Caught unknown exception.\n"; return 1; } } <commit_msg>added subfunctions for testing binary read/write of populations<commit_after>// // simrecomb.cpp // // Copyright 2012 Darren Kessner // // 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 "Population.hpp" #include <iostream> #include <cstring> #include <fstream> #include <sstream> #include <map> #include "boost/filesystem.hpp" #include "boost/filesystem/fstream.hpp" using namespace std; using boost::shared_ptr; namespace bfs = boost::filesystem; struct SimulationConfig { unsigned int seed; vector<string> geneticMapFilenames; vector< vector<Population::Config> > populationConfigs; // each generation is a vector<Population::Config> SimulationConfig() : seed(0) {} }; ostream& operator<<(ostream& os, const SimulationConfig& simulationConfig) { os << "seed " << simulationConfig.seed << endl << endl; os << "geneticMapFilenames " << simulationConfig.geneticMapFilenames.size() << endl; for (vector<string>::const_iterator it=simulationConfig.geneticMapFilenames.begin(); it!=simulationConfig.geneticMapFilenames.end(); ++it) os << "geneticMapFilename " << *it << endl; os << endl; for (size_t i=0; i<simulationConfig.populationConfigs.size(); i++) { os << "generation " << i << endl; copy(simulationConfig.populationConfigs[i].begin(), simulationConfig.populationConfigs[i].end(), ostream_iterator<Population::Config>(os,"\n")); os << endl; } return os; } istream& operator>>(istream& is, SimulationConfig& simulationConfig) { while (is) { // parse line by line string buffer; getline(is, buffer); if (!is) return is; vector<string> tokens; istringstream iss(buffer); copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(tokens)); // switch on first token if (tokens.empty()) continue; else if (tokens[0] == "seed" && tokens.size() == 2) simulationConfig.seed = atoi(tokens[1].c_str()); else if (tokens[0] == "geneticMapFilenames") continue; else if (tokens[0] == "geneticMapFilename" && tokens.size()==2) simulationConfig.geneticMapFilenames.push_back(tokens[1]); else if (tokens[0] == "generation") simulationConfig.populationConfigs.push_back(vector<Population::Config>()); else if (tokens[0] == "population") { simulationConfig.populationConfigs.back().push_back(Population::Config()); istringstream temp(buffer); temp >> simulationConfig.populationConfigs.back().back(); } else cerr << "Ignoring invalid configuration line:\n" << buffer << endl; } return is; } void printPopulations(ostream& os, const Populations& populations, const string& label) { os << "<" << label << ">\n"; for (size_t i=0; i<populations.size(); i++) { os << "<population" << i << ">\n" << *populations[i] << "</population" << i << ">\n"; } os << "</" << label << ">\n"; } void initializeExampleSimulationConfig(SimulationConfig& simulationConfig) { const size_t chromosomePairCount_ = 3; const unsigned int populationSize_ = 10000; const double admixtureProportion_ = .8; // fraction of genes from 1st population for (size_t i=0; i<chromosomePairCount_; i++) simulationConfig.geneticMapFilenames.push_back("genetic_map_chr21_b36.txt"); // hack // generation 0 (ancestral populations) simulationConfig.populationConfigs.push_back(vector<Population::Config>(3)); Population::Config* config = &simulationConfig.populationConfigs[0][0]; config->size = 0; config->populationID = 0; config = &simulationConfig.populationConfigs[0][1]; config->size = populationSize_; config->populationID = 1; config->chromosomePairCount = chromosomePairCount_; config = &simulationConfig.populationConfigs[0][2]; config->size = populationSize_; config->populationID = 2; config->chromosomePairCount = chromosomePairCount_; // generation 1 (initial admixture) simulationConfig.populationConfigs.push_back(vector<Population::Config>(1)); config = &simulationConfig.populationConfigs[1][0]; config->size = populationSize_; double p = admixtureProportion_; config->matingDistribution.push_back(p*p, make_pair(1,1)); config->matingDistribution.push_back(2*p*(1-p), make_pair(1,2)); config->matingDistribution.push_back((1-p)*(1-p), make_pair(2,2)); // subsequent generations - just recombination for (size_t generation=2; generation<8; generation++) { simulationConfig.populationConfigs.push_back(vector<Population::Config>(1)); config = &simulationConfig.populationConfigs[generation][0]; config->size = populationSize_; config->matingDistribution.push_back(1, make_pair(0,0)); } } void initializeRecombinationMaps(const SimulationConfig& simulationConfig, const Random& random) { Organism::recombinationPositionGenerator_ = shared_ptr<RecombinationPositionGenerator>( new RecombinationPositionGenerator_RecombinationMap(simulationConfig.geneticMapFilenames, random)); } shared_ptr<Populations> createPopulations(shared_ptr<Populations> current, const vector<Population::Config>& populationConfigs, const Random& random) { shared_ptr<Populations> result(new Populations); for (vector<Population::Config>::const_iterator it=populationConfigs.begin(); it!=populationConfigs.end(); ++it) { if (!current.get()) result->push_back(shared_ptr<Population>(new Population(*it))); else result->push_back(shared_ptr<Population>(new Population(*it, *current, random))); } return result; } void simulate(const SimulationConfig& simulationConfig, bfs::path outputDirectory) { bfs::ofstream osSimulationConfig(outputDirectory / "simrecomb_config.txt"); osSimulationConfig << simulationConfig; osSimulationConfig.close(); Random random(simulationConfig.seed); cout << "Initializing recombination maps.\n"; initializeRecombinationMaps(simulationConfig, random); bfs::ofstream osLog(outputDirectory / "log.txt"); shared_ptr<Populations> current; for (size_t generation=0; generation<simulationConfig.populationConfigs.size(); generation++) { cout << "Generation " << generation << endl; shared_ptr<Populations> next = createPopulations(current, simulationConfig.populationConfigs[generation], random); current = next; ostringstream label; label << "gen" << generation; //printPopulations(osLog, *current, label.str()); osLog << generation << endl; } osLog.close(); // output the last generation for (size_t i=0; i<current->size(); ++i) { ostringstream filename; filename << "pop" << i << ".txt"; bfs::ofstream os_pop(outputDirectory / filename.str()); os_pop << *(*current)[i]; } } int main(int argc, char* argv[]) { try { ostringstream usage; usage << "Usage: simrecomb <subfunction> [args]\n"; usage << endl; usage << "Print example config file to stdout:\n"; usage << " simrecomb example\n"; usage << endl; usage << "Run simulation:\n"; usage << " simrecomb sim <config_filename> <outputdir>\n"; usage << endl; usage << "Darren Kessner\n"; usage << "John Novembre Lab, UCLA\n"; string subfunction = argc>1 ? argv[1] : ""; if (subfunction == "sim") { if (argc < 4) throw runtime_error(usage.str().c_str()); string configFilename = argv[2]; string outputDirectory = argv[3]; if (!bfs::exists(configFilename)) throw runtime_error(("[simrecomb] Config file not found: " + configFilename).c_str()); if (bfs::exists(outputDirectory)) throw runtime_error(("[simrecomb] Directory exists: " + outputDirectory).c_str()); cout << "Reading configuration file " << configFilename << endl; bfs::ifstream is(configFilename); SimulationConfig simulationConfig; is >> simulationConfig; is.close(); bfs::create_directories(outputDirectory); simulate(simulationConfig, outputDirectory); } else if (subfunction == "example") { SimulationConfig temp; initializeExampleSimulationConfig(temp); cout << temp; } else if (subfunction == "txt2pop") { if (argc < 4) throw runtime_error(usage.str().c_str()); string filename_in = argv[2]; string filename_out = argv[3]; cout << "reading " << filename_in << endl << flush; ifstream is(filename_in.c_str()); if (!is) throw runtime_error(("[simrecomb] Unable to open file " + filename_in).c_str()); Population p; is >> p; cout << "writing " << filename_out << endl << flush; ofstream os(filename_out.c_str(), ios::binary); p.write(os); os.close(); } else if (subfunction == "pop2txt") { if (argc < 4) throw runtime_error(usage.str().c_str()); string filename_in = argv[2]; string filename_out = argv[3]; cout << "reading " << filename_in << endl << flush; ifstream is(filename_in.c_str(), ios::binary); if (!is) throw runtime_error(("[simrecomb] Unable to open file " + filename_in).c_str()); Population p; p.read(is); cout << "writing " << filename_out << endl << flush; ofstream os(filename_out.c_str()); os << p; os.close(); } else { throw runtime_error(usage.str().c_str()); } return 0; } catch(exception& e) { cerr << e.what() << endl; return 1; } catch(...) { cerr << "Caught unknown exception.\n"; return 1; } } <|endoftext|>
<commit_before><commit_msg>sal_Bool->bool<commit_after><|endoftext|>
<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <string> #include <x86intrin.h> #include <utils.hpp> #include <Observation.hpp> #ifndef SNR_HPP #define SNR_HPP namespace PulsarSearch { template< typename T > using snrFunc = void (*)(const AstroData::Observation< T > &, const float *, float *); // Sequential SNR template< typename T > void snrFoldedTS(const AstroData::Observation< T > & observation, const std::vector< T > & foldedTS, std::vector< T > & snrs); // OpenCL SNR template< typename T > std::string * getSNROpenCL(const unsigned int nrDMsPerBlock, const unsigned int nrPeriodsPerBlock, const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, std::string & dataType, const AstroData::Observation< T > & observation); // SIMD SNR std::string * getSNRSIMD(const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, bool phi = false); // Implementations template< typename T > void snrFoldedTS(AstroData::Observation< T > & observation, const std::vector< T > & foldedTS, std::vector< T > & snrs) { for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) { for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) { T max = 0; float average = 0.0f; float rms = 0.0f; for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) { T value = foldedTS[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + dm]; average += value; rms += (value * value); if ( value > max ) { max = value; } } average /= observation.getNrBins(); rms = sqrt(rms / observation.getNrBins()); snrs[(period * observation.getNrPaddedDMs()) + dm] = (max - average) / rms; } } } template< typename T > std::string * getSNROpenCL(const unsigned int nrDMsPerBlock, const unsigned int nrPeriodsPerBlock, const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, std::string & dataType, const AstroData::Observation< T > & observation) { std::string * code = new std::string(); // Begin kernel's template std::string nrPaddedDMs_s = isa::utils::toString< unsigned int >(observation.getNrPaddedDMs()); std::string nrBinsInverse_s = isa::utils::toString< float >(1.0f / observation.getNrBins()); *code = "__kernel void snr(__global const " + dataType + " * const restrict foldedData, __global " + dataType + " * const restrict snrs) {\n" "<%DEF_DM%>" "<%DEF_PERIOD%>" + dataType + " globalItem = 0;\n" + dataType + " average = 0;\n" + dataType + " rms = 0;\n" + dataType + " max = 0;\n" "\n" "<%COMPUTE%>" "}\n"; std::string defDMsTemplate = "const unsigned int dm<%DM_NUM%> = (get_group_id(0) * " + isa::utils::toString< unsigned int >(nrDMsPerBlock * nrDMsPerThread) + ") + get_local_id(0) + <%DM_NUM%>;\n"; std::string defPeriodsTemplate = "const unsigned int period<%PERIOD_NUM%> = (get_group_id(1) * " + isa::utils::toString< unsigned int >(nrPeriodsPerBlock * nrPeriodsPerThread) + ") + get_local_id(1) + <%PERIOD_NUM%>;\n"; std::string computeTemplate = "average = 0;\n" " rms = 0;\n" " max = 0;\n" "for ( unsigned int bin = 0; bin < " + isa::utils::toString< unsigned int >(observation.getNrBins()) + "; bin++ ) {\n" "globalItem = foldedData[(bin * " + isa::utils::toString< unsigned int >(observation.getNrPeriods()) + " * " + nrPaddedDMs_s + ") + ((period + <%PERIOD_NUM%>) * " + nrPaddedDMs_s + ") + dm + <%DM_NUM%>];\n" "average += globalItem;\n" "rms += (globalItem * globalItem);\n" "max = fmax(max, globalItem);\n" "}\n" "average *= " + nrBinsInverse_s + "f;\n" "rms *= " + nrBinsInverse_s + "f;\n" "snrs[((period + <%PERIOD_NUM%>) * " + nrPaddedDMs_s + ") + dm + <%DM_NUM%>] = (max - average) / native_sqrt(rms);\n"; // End kernel's template std::string * defDM_s = new std::string(); std::string * defPeriod_s = new std::string(); std::string * compute_s = new std::string(); for ( unsigned int dm = 0; dm < nrDMsPerThread; dm++ ) { std::string dm_s = isa::utils::toString< unsigned int >(dm); std::string * temp_s = 0; temp_s = isa::utils::replace(&defDMsTemplate, "<%DM_NUM%>", dm_s); defDM_s->append(*temp_s); delete temp_s; } for ( unsigned int period = 0; period < nrPeriodsPerThread; period++ ) { std::string period_s = isa::utils::toString< unsigned int >(period); std::string * temp_s = 0; temp_s = isa::utils::replace(&defPeriodsTemplate, "<%PERIOD_NUM%>", period_s); defPeriod_s->append(*temp_s); delete temp_s; for ( unsigned int dm = 0; dm < nrDMsPerThread; dm++ ) { std::string dm_s = isa::utils::toString< unsigned int >(dm); temp_s = isa::utils::replace(&computeTemplate, "<%PERIOD_NUM%>", period_s); temp_s = isa::utils::replace(temp_s, "<%DM_NUM%>", dm_s, true); compute_s->append(*temp_s); delete temp_s; } } code = isa::utils::replace(code, "<%DEF_DM%>", *defDM_s, true); code = isa::utils::replace(code, "<%DEF_PERIOD%>", *defPeriod_s, true); code = isa::utils::replace(code, "<%COMPUTE%>", *compute_s, true); return code; } std::string * getSNRSIMD(const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, bool phi) { std::string * code = new std::string(); std::string * computeTemplate = new string(); // Begin kernel's template if ( !phi ) { *code = "namespace PulsarSearch {\n" "template< typename T > void snrAVX" + isa::utils::toString(nrDMsPerThread) + "x" + isa::utils::toString(nrPeriodsPerThread) + "(const AstroData::Observation< T > & observation, const float * const __restrict__ foldedData, float * const __restrict__ snrs) {\n" "{\n" "__m256 max = _mm256_setzero_ps();\n" "__m256 average = _mm256_setzero_ps();\n" "__m256 rms = _mm256_setzero_ps();\n" "#pragma omp parallel for schedule(static)\n" "for ( unsigned int period = 0; period < observation.getNrPeriods(); period += " + isa::utils::toString(nrPeriodsPerThread) + ") {\n" "#pragma omp parallel for schedule(static)\n" "for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm += " + isa::utils::toString(nrPeriodsPerThread) + " * 8) {\n" "<%COMPUTE%>" "}\n" "}\n" "}\n" "}\n" "}\n"; *computeTemplate = "max = _mm256_setzero_ps();\n" "average = _mm256_setzero_ps();\n" "rms = _mm256_setzero_ps();\n" "\n" "for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\n" "__m256 value = _mm256_load_ps(&(foldedData[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + ((period + <%PERIOD_NUM%>) * observation.getNrPaddedDMs()) + dm + <%DM_NUM%>]));\n" "\n" "average = _mm256_add_ps(average, value);\n" "rms = _mm256_add_ps(rms, _mm256_mul_ps(value, value));\n" "max = _mm256_max_ps(max, value);\n" "}\n" "average = _mm256_div_ps(average, _mm256_set1_ps(observation.getNrBins()));\n" "rms = _mm256_sqrt_ps(_mm256_div_ps(rms, _mm256_set1_ps(observation.getNrBins())));\n" "_mm256_store_ps(&(snrs[((period + <%PERIOD_NUM%>) * " + nrPaddedDMs_s + ") + dm + <%DM_NUM%>]),_mm256_div_ps(_mm256_sub_ps(max, average), rms));\n"; } else { *code = "namespace PulsarSearch {\n" "template< typename T > void snrPhi" + isa::utils::toString(nrDMsPerThread) + "x" + isa::utils::toString(nrPeriodsPerThread) + "(const AstroData::Observation< T > & observation, const float * const __restrict__ foldedData, float * const __restrict__ snrs) {\n" "{\n" "__m512 max = _mm512_setzero_ps();\n" "__m512 average = _mm512_setzero_ps();\n" "__m512 rms = _mm512_setzero_ps();\n" "#pragma omp parallel for schedule(static)\n" "for ( unsigned int period = 0; period < observation.getNrPeriods(); period += " + isa::utils::toString(nrPeriodsPerThread) + ") {\n" "#pragma omp parallel for schedule(static)\n" "for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm += " + isa::utils::toString(nrPeriodsPerThread) + " * 16) {\n" "<%COMPUTE%>" "}\n" "}\n" "}\n" "}\n" "}\n"; *computeTemplate = "max = _mm512_setzero_ps();\n" "average = _mm512_setzero_ps();\n" "rms = _mm512_setzero_ps();\n" "\n" "for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\n" "__m512 value = _mm512_load_ps(&(foldedData[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + ((period + <%PERIOD_NUM%>) * observation.getNrPaddedDMs()) + dm + <%DM_NUM%>]));\n" "\n" "average = _mm512_add_ps(average, value);\n" "rms = _mm512_add_ps(rms, _mm512_mul_ps(value, value));\n" "max = _mm512_max_ps(max, value);\n" "}\n" "average = _mm512_div_ps(average, _mm512_set1_ps(observation.getNrBins()));\n" "rms = _mm512_sqrt_ps(_mm512_div_ps(rms, _mm512_set1_ps(observation.getNrBins())));\n" "_mm512_store_ps(&(snrs[((period + <%PERIOD_NUM%>) * " + nrPaddedDMs_s + ") + dm + <%DM_NUM%>]),_mm512_div_ps(_mm512_sub_ps(max, average), rms));\n"; } // End kernel's template std::string * compute_s = new std::string(); for ( unsigned int period = 0; period < nrPeriodsPerThread; period++ ) { std::string period_s = isa::utils::toString< unsigned int >(period); for ( unsigned int dm = 0; dm < nrDMsPerThread; dm++ ) { std::string dm_s = isa::utils::toString< unsigned int >(dm); std::string * temp_s = 0; temp_s = isa::utils::replace(computeTemplate, "<%PERIOD_NUM%>", period_s); temp_s = isa::utils::replace(temp_s, "<%DM_NUM%>", dm_s, true); compute_s->append(*temp_s); delete temp_s; } } code = isa::utils::replace(code, "<%COMPUTE%>", *compute_s, true); delete compute_s; delete computeTemplate; return code; } } // PulsarSearch #endif // SNR_HPP <commit_msg>Fixing a bug in SIMD code generation.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <string> #include <x86intrin.h> #include <utils.hpp> #include <Observation.hpp> #ifndef SNR_HPP #define SNR_HPP namespace PulsarSearch { template< typename T > using snrFunc = void (*)(const AstroData::Observation< T > &, const float *, float *); // Sequential SNR template< typename T > void snrFoldedTS(const AstroData::Observation< T > & observation, const std::vector< T > & foldedTS, std::vector< T > & snrs); // OpenCL SNR template< typename T > std::string * getSNROpenCL(const unsigned int nrDMsPerBlock, const unsigned int nrPeriodsPerBlock, const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, std::string & dataType, const AstroData::Observation< T > & observation); // SIMD SNR std::string * getSNRSIMD(const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, bool phi = false); // Implementations template< typename T > void snrFoldedTS(AstroData::Observation< T > & observation, const std::vector< T > & foldedTS, std::vector< T > & snrs) { for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) { for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) { T max = 0; float average = 0.0f; float rms = 0.0f; for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) { T value = foldedTS[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + dm]; average += value; rms += (value * value); if ( value > max ) { max = value; } } average /= observation.getNrBins(); rms = sqrt(rms / observation.getNrBins()); snrs[(period * observation.getNrPaddedDMs()) + dm] = (max - average) / rms; } } } template< typename T > std::string * getSNROpenCL(const unsigned int nrDMsPerBlock, const unsigned int nrPeriodsPerBlock, const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, std::string & dataType, const AstroData::Observation< T > & observation) { std::string * code = new std::string(); // Begin kernel's template std::string nrPaddedDMs_s = isa::utils::toString< unsigned int >(observation.getNrPaddedDMs()); std::string nrBinsInverse_s = isa::utils::toString< float >(1.0f / observation.getNrBins()); *code = "__kernel void snr(__global const " + dataType + " * const restrict foldedData, __global " + dataType + " * const restrict snrs) {\n" "<%DEF_DM%>" "<%DEF_PERIOD%>" + dataType + " globalItem = 0;\n" + dataType + " average = 0;\n" + dataType + " rms = 0;\n" + dataType + " max = 0;\n" "\n" "<%COMPUTE%>" "}\n"; std::string defDMsTemplate = "const unsigned int dm<%DM_NUM%> = (get_group_id(0) * " + isa::utils::toString< unsigned int >(nrDMsPerBlock * nrDMsPerThread) + ") + get_local_id(0) + <%DM_NUM%>;\n"; std::string defPeriodsTemplate = "const unsigned int period<%PERIOD_NUM%> = (get_group_id(1) * " + isa::utils::toString< unsigned int >(nrPeriodsPerBlock * nrPeriodsPerThread) + ") + get_local_id(1) + <%PERIOD_NUM%>;\n"; std::string computeTemplate = "average = 0;\n" " rms = 0;\n" " max = 0;\n" "for ( unsigned int bin = 0; bin < " + isa::utils::toString< unsigned int >(observation.getNrBins()) + "; bin++ ) {\n" "globalItem = foldedData[(bin * " + isa::utils::toString< unsigned int >(observation.getNrPeriods()) + " * " + nrPaddedDMs_s + ") + ((period + <%PERIOD_NUM%>) * " + nrPaddedDMs_s + ") + dm + <%DM_NUM%>];\n" "average += globalItem;\n" "rms += (globalItem * globalItem);\n" "max = fmax(max, globalItem);\n" "}\n" "average *= " + nrBinsInverse_s + "f;\n" "rms *= " + nrBinsInverse_s + "f;\n" "snrs[((period + <%PERIOD_NUM%>) * " + nrPaddedDMs_s + ") + dm + <%DM_NUM%>] = (max - average) / native_sqrt(rms);\n"; // End kernel's template std::string * defDM_s = new std::string(); std::string * defPeriod_s = new std::string(); std::string * compute_s = new std::string(); for ( unsigned int dm = 0; dm < nrDMsPerThread; dm++ ) { std::string dm_s = isa::utils::toString< unsigned int >(dm); std::string * temp_s = 0; temp_s = isa::utils::replace(&defDMsTemplate, "<%DM_NUM%>", dm_s); defDM_s->append(*temp_s); delete temp_s; } for ( unsigned int period = 0; period < nrPeriodsPerThread; period++ ) { std::string period_s = isa::utils::toString< unsigned int >(period); std::string * temp_s = 0; temp_s = isa::utils::replace(&defPeriodsTemplate, "<%PERIOD_NUM%>", period_s); defPeriod_s->append(*temp_s); delete temp_s; for ( unsigned int dm = 0; dm < nrDMsPerThread; dm++ ) { std::string dm_s = isa::utils::toString< unsigned int >(dm); temp_s = isa::utils::replace(&computeTemplate, "<%PERIOD_NUM%>", period_s); temp_s = isa::utils::replace(temp_s, "<%DM_NUM%>", dm_s, true); compute_s->append(*temp_s); delete temp_s; } } code = isa::utils::replace(code, "<%DEF_DM%>", *defDM_s, true); code = isa::utils::replace(code, "<%DEF_PERIOD%>", *defPeriod_s, true); code = isa::utils::replace(code, "<%COMPUTE%>", *compute_s, true); return code; } std::string * getSNRSIMD(const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, bool phi) { std::string * code = new std::string(); std::string * computeTemplate = new string(); // Begin kernel's template if ( !phi ) { *code = "namespace PulsarSearch {\n" "template< typename T > void snrAVX" + isa::utils::toString(nrDMsPerThread) + "x" + isa::utils::toString(nrPeriodsPerThread) + "(const AstroData::Observation< T > & observation, const float * const __restrict__ foldedData, float * const __restrict__ snrs) {\n" "{\n" "__m256 max = _mm256_setzero_ps();\n" "__m256 average = _mm256_setzero_ps();\n" "__m256 rms = _mm256_setzero_ps();\n" "#pragma omp parallel for schedule(static)\n" "for ( unsigned int period = 0; period < observation.getNrPeriods(); period += " + isa::utils::toString(nrPeriodsPerThread) + ") {\n" "#pragma omp parallel for schedule(static)\n" "for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm += " + isa::utils::toString(nrPeriodsPerThread) + " * 8) {\n" "<%COMPUTE%>" "}\n" "}\n" "}\n" "}\n" "}\n"; *computeTemplate = "max = _mm256_setzero_ps();\n" "average = _mm256_setzero_ps();\n" "rms = _mm256_setzero_ps();\n" "\n" "for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\n" "__m256 value = _mm256_load_ps(&(foldedData[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + ((period + <%PERIOD_NUM%>) * observation.getNrPaddedDMs()) + dm + <%DM_NUM%>]));\n" "\n" "average = _mm256_add_ps(average, value);\n" "rms = _mm256_add_ps(rms, _mm256_mul_ps(value, value));\n" "max = _mm256_max_ps(max, value);\n" "}\n" "average = _mm256_div_ps(average, _mm256_set1_ps(observation.getNrBins()));\n" "rms = _mm256_sqrt_ps(_mm256_div_ps(rms, _mm256_set1_ps(observation.getNrBins())));\n" "_mm256_store_ps(&(snrs[((period + <%PERIOD_NUM%>) * observation.getNrPaddedDMs()) + dm + <%DM_NUM%>]),_mm256_div_ps(_mm256_sub_ps(max, average), rms));\n"; } else { *code = "namespace PulsarSearch {\n" "template< typename T > void snrPhi" + isa::utils::toString(nrDMsPerThread) + "x" + isa::utils::toString(nrPeriodsPerThread) + "(const AstroData::Observation< T > & observation, const float * const __restrict__ foldedData, float * const __restrict__ snrs) {\n" "{\n" "__m512 max = _mm512_setzero_ps();\n" "__m512 average = _mm512_setzero_ps();\n" "__m512 rms = _mm512_setzero_ps();\n" "#pragma omp parallel for schedule(static)\n" "for ( unsigned int period = 0; period < observation.getNrPeriods(); period += " + isa::utils::toString(nrPeriodsPerThread) + ") {\n" "#pragma omp parallel for schedule(static)\n" "for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm += " + isa::utils::toString(nrPeriodsPerThread) + " * 16) {\n" "<%COMPUTE%>" "}\n" "}\n" "}\n" "}\n" "}\n"; *computeTemplate = "max = _mm512_setzero_ps();\n" "average = _mm512_setzero_ps();\n" "rms = _mm512_setzero_ps();\n" "\n" "for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\n" "__m512 value = _mm512_load_ps(&(foldedData[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + ((period + <%PERIOD_NUM%>) * observation.getNrPaddedDMs()) + dm + <%DM_NUM%>]));\n" "\n" "average = _mm512_add_ps(average, value);\n" "rms = _mm512_add_ps(rms, _mm512_mul_ps(value, value));\n" "max = _mm512_max_ps(max, value);\n" "}\n" "average = _mm512_div_ps(average, _mm512_set1_ps(observation.getNrBins()));\n" "rms = _mm512_sqrt_ps(_mm512_div_ps(rms, _mm512_set1_ps(observation.getNrBins())));\n" "_mm512_store_ps(&(snrs[((period + <%PERIOD_NUM%>) * observation.getNrPaddedDMs()) + dm + <%DM_NUM%>]),_mm512_div_ps(_mm512_sub_ps(max, average), rms));\n"; } // End kernel's template std::string * compute_s = new std::string(); for ( unsigned int period = 0; period < nrPeriodsPerThread; period++ ) { std::string period_s = isa::utils::toString< unsigned int >(period); for ( unsigned int dm = 0; dm < nrDMsPerThread; dm++ ) { std::string dm_s = isa::utils::toString< unsigned int >(dm); std::string * temp_s = 0; temp_s = isa::utils::replace(computeTemplate, "<%PERIOD_NUM%>", period_s); temp_s = isa::utils::replace(temp_s, "<%DM_NUM%>", dm_s, true); compute_s->append(*temp_s); delete temp_s; } } code = isa::utils::replace(code, "<%COMPUTE%>", *compute_s, true); delete compute_s; delete computeTemplate; return code; } } // PulsarSearch #endif // SNR_HPP <|endoftext|>
<commit_before>#include <QCommandLineParser> #include <QCoreApplication> #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QTimer> #include "functions.h" #include "logger.h" #include "models/api/api.h" #include "models/page.h" #include "models/page-api.h" #include "models/profile.h" #include "models/site.h" #include "models/source.h" #include "tags/tag.h" bool opCompare(const QString &op, int left, int right) { if (right == -1) { return true; } if (op == ">") { return left > right; } if (op == "<") { return left < right; } return left == right; } bool jsonCompare(const QVariant &value, QJsonValue opt) { QString op = "="; if (opt.isArray()) { QJsonArray arrOpt = opt.toArray(); op = arrOpt[0].toString(); opt = arrOpt[1]; } if (value.type() == QVariant::String) { return value.toString() == opt.toString(); } return opCompare(op, value.toInt(), opt.toInt()); } int main(int argc, char *argv[]) { const QCoreApplication app(argc, argv); QCommandLineParser parser; parser.addHelpOption(); const QCommandLineOption inputOption(QStringList() << "i" << "input", "Input JSON configuration file", "input"); const QCommandLineOption outputOption(QStringList() << "o" << "output", "Output JSON result file", "output"); parser.addOption(inputOption); parser.addOption(outputOption); parser.process(app); Logger::getInstance().setLogLevel(Logger::Warning); QFile f(parser.value(inputOption)); if (!f.open(QFile::ReadOnly | QFile::Text)) { return 1; } QJsonObject allJson; QJsonDocument input = QJsonDocument::fromJson(f.readAll()); f.close(); Profile *profile = new Profile(savePath()); auto allSources = profile->getSources(); auto allSites = profile->getSites(); const auto oldBlacklist = profile->getBlacklist(); profile->setBlacklistedTags(Blacklist()); const QJsonObject root = input.object(); const QJsonArray rootSearch = root.value("search").toArray(); const QJsonObject sources = root.value("sources").toObject(); for (auto it = sources.constBegin(); it != sources.constEnd(); ++it) { const QString &sourceName = it.key(); qDebug() << "#" << "Source" << sourceName; QJsonObject sourceJson; Source *source = allSources.value(sourceName); QJsonObject sites = it.value().toObject(); const QJsonObject sourceApis = sites.value("apis").toObject(); QJsonArray sourceSearch = rootSearch; if (sites.contains("search")) { sourceSearch = sites.value("search").toArray(); } for (Site *site : source->getSites()) { qDebug() << "##" << "Site" << site->url(); QJsonObject siteJson; QJsonObject siteApis = sourceApis; QJsonArray siteSearch = sourceSearch; if (sites.contains(site->url())) { QJsonObject override = sites.value(site->url()).toObject(); if (override.contains("apis")) { siteApis = override.value("apis").toObject(); } if (override.contains("search")) { siteSearch = override.value("search").toArray(); } } for (auto ita = siteApis.constBegin(); ita != siteApis.constEnd(); ++ita) { const QString &apiName = ita.key(); qDebug() << "###" << "API" << apiName; QJsonObject apiJson; QJsonArray checks = ita.value().toArray(); QJsonArray apiSearch = siteSearch; if (checks.count() > 4) { apiSearch = checks[4].toArray(); } const QString search = apiSearch[0].toString(); const int pageI = apiSearch[1].toInt(); const int limit = apiSearch[2].toInt(); Api *api = nullptr; for (Api *a : site->getApis()) { if (a->getName().toLower() == apiName.toLower()) { api = a; } } if (api == nullptr) { continue; } auto page = new Page(profile, site, allSites.values(), QStringList() << search, pageI, limit); auto pageApi = new PageApi(page, profile, site, api, search.split(' '), pageI, limit); QEventLoop loop; QObject::connect(pageApi, &PageApi::finishedLoading, &loop, &QEventLoop::quit); QTimer::singleShot(1, pageApi, SLOT(load())); loop.exec(); apiJson["status"] = "ok"; QStringList message; // Checks if (!jsonCompare(pageApi->errors().join(", "), checks[0])) { apiJson["status"] = "error"; message.append(pageApi->errors()); } if (!jsonCompare(pageApi->imagesCount(false), checks[1])) { if (apiJson["status"] == "ok") { apiJson["status"] = "warning"; } message.append("Image count error: " + QString::number(pageApi->imagesCount(false))); } if (!jsonCompare(pageApi->images().count(), checks[2])) { apiJson["status"] = "error"; message.append("Number of images error: " + QString::number(pageApi->images().count())); } if (!jsonCompare(pageApi->tags().count(), checks[3])) { if (apiJson["status"] == "ok") { apiJson["status"] = "warning"; } QStringList tags; for (const Tag& tag : pageApi->tags()) { tags.append(tag.text()); } message.append("Number of tags error: " + QString::number(pageApi->tags().count()) + " [" + tags.join(", ") + "]"); } if (!message.isEmpty()) { apiJson["message"] = message.join(", "); siteJson[apiName] = apiJson; } else { siteJson[apiName] = apiJson["status"]; } pageApi->deleteLater(); page->deleteLater(); } sourceJson[site->url()] = siteJson; } allJson[sourceName] = sourceJson; } profile->setBlacklistedTags(oldBlacklist); QJsonDocument outDoc(allJson); QFile fOut(parser.value(outputOption)); if (!fOut.open(QFile::WriteOnly | QFile::Truncate | QFile::Text)) { return 1; } fOut.write(outDoc.toJson()); fOut.close(); return 0; } <commit_msg>Fix missing E2E includes<commit_after>#include <QCommandLineParser> #include <QCoreApplication> #include <QFile> #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QStringList> #include <QTimer> #include "functions.h" #include "logger.h" #include "models/api/api.h" #include "models/page.h" #include "models/page-api.h" #include "models/profile.h" #include "models/site.h" #include "models/source.h" #include "tags/tag.h" bool opCompare(const QString &op, int left, int right) { if (right == -1) { return true; } if (op == ">") { return left > right; } if (op == "<") { return left < right; } return left == right; } bool jsonCompare(const QVariant &value, QJsonValue opt) { QString op = "="; if (opt.isArray()) { QJsonArray arrOpt = opt.toArray(); op = arrOpt[0].toString(); opt = arrOpt[1]; } if (value.type() == QVariant::String) { return value.toString() == opt.toString(); } return opCompare(op, value.toInt(), opt.toInt()); } int main(int argc, char *argv[]) { const QCoreApplication app(argc, argv); QCommandLineParser parser; parser.addHelpOption(); const QCommandLineOption inputOption(QStringList() << "i" << "input", "Input JSON configuration file", "input"); const QCommandLineOption outputOption(QStringList() << "o" << "output", "Output JSON result file", "output"); parser.addOption(inputOption); parser.addOption(outputOption); parser.process(app); Logger::getInstance().setLogLevel(Logger::Warning); QFile f(parser.value(inputOption)); if (!f.open(QFile::ReadOnly | QFile::Text)) { return 1; } QJsonObject allJson; QJsonDocument input = QJsonDocument::fromJson(f.readAll()); f.close(); Profile *profile = new Profile(savePath()); auto allSources = profile->getSources(); auto allSites = profile->getSites(); const auto oldBlacklist = profile->getBlacklist(); profile->setBlacklistedTags(Blacklist()); const QJsonObject root = input.object(); const QJsonArray rootSearch = root.value("search").toArray(); const QJsonObject sources = root.value("sources").toObject(); for (auto it = sources.constBegin(); it != sources.constEnd(); ++it) { const QString &sourceName = it.key(); qDebug() << "#" << "Source" << sourceName; QJsonObject sourceJson; Source *source = allSources.value(sourceName); QJsonObject sites = it.value().toObject(); const QJsonObject sourceApis = sites.value("apis").toObject(); QJsonArray sourceSearch = rootSearch; if (sites.contains("search")) { sourceSearch = sites.value("search").toArray(); } for (Site *site : source->getSites()) { qDebug() << "##" << "Site" << site->url(); QJsonObject siteJson; QJsonObject siteApis = sourceApis; QJsonArray siteSearch = sourceSearch; if (sites.contains(site->url())) { QJsonObject override = sites.value(site->url()).toObject(); if (override.contains("apis")) { siteApis = override.value("apis").toObject(); } if (override.contains("search")) { siteSearch = override.value("search").toArray(); } } for (auto ita = siteApis.constBegin(); ita != siteApis.constEnd(); ++ita) { const QString &apiName = ita.key(); qDebug() << "###" << "API" << apiName; QJsonObject apiJson; QJsonArray checks = ita.value().toArray(); QJsonArray apiSearch = siteSearch; if (checks.count() > 4) { apiSearch = checks[4].toArray(); } const QString search = apiSearch[0].toString(); const int pageI = apiSearch[1].toInt(); const int limit = apiSearch[2].toInt(); Api *api = nullptr; for (Api *a : site->getApis()) { if (a->getName().toLower() == apiName.toLower()) { api = a; } } if (api == nullptr) { continue; } auto page = new Page(profile, site, allSites.values(), QStringList() << search, pageI, limit); auto pageApi = new PageApi(page, profile, site, api, search.split(' '), pageI, limit); QEventLoop loop; QObject::connect(pageApi, &PageApi::finishedLoading, &loop, &QEventLoop::quit); QTimer::singleShot(1, pageApi, SLOT(load())); loop.exec(); apiJson["status"] = "ok"; QStringList message; // Checks if (!jsonCompare(pageApi->errors().join(", "), checks[0])) { apiJson["status"] = "error"; message.append(pageApi->errors()); } if (!jsonCompare(pageApi->imagesCount(false), checks[1])) { if (apiJson["status"] == "ok") { apiJson["status"] = "warning"; } message.append("Image count error: " + QString::number(pageApi->imagesCount(false))); } if (!jsonCompare(pageApi->images().count(), checks[2])) { apiJson["status"] = "error"; message.append("Number of images error: " + QString::number(pageApi->images().count())); } if (!jsonCompare(pageApi->tags().count(), checks[3])) { if (apiJson["status"] == "ok") { apiJson["status"] = "warning"; } QStringList tags; for (const Tag& tag : pageApi->tags()) { tags.append(tag.text()); } message.append("Number of tags error: " + QString::number(pageApi->tags().count()) + " [" + tags.join(", ") + "]"); } if (!message.isEmpty()) { apiJson["message"] = message.join(", "); siteJson[apiName] = apiJson; } else { siteJson[apiName] = apiJson["status"]; } pageApi->deleteLater(); page->deleteLater(); } sourceJson[site->url()] = siteJson; } allJson[sourceName] = sourceJson; } profile->setBlacklistedTags(oldBlacklist); QJsonDocument outDoc(allJson); QFile fOut(parser.value(outputOption)); if (!fOut.open(QFile::WriteOnly | QFile::Truncate | QFile::Text)) { return 1; } fOut.write(outDoc.toJson()); fOut.close(); return 0; } <|endoftext|>
<commit_before><commit_msg>Avoid OS X sandbox messages when just checking if a pathname is a directory<commit_after><|endoftext|>
<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON) // Copyright 2017 Netherlands eScience Center // // 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 <configuration.hpp> #include <CommandLine.hpp> #include <Kernels.hpp> #include <Memory.hpp> #include <Pipeline.hpp> int main(int argc, char * argv[]) { // Command line options Options options {}; DeviceOptions deviceOptions {}; DataOptions dataOptions {}; GeneratorOptions generatorOptions {}; // Memory HostMemory hostMemory {}; DeviceMemory deviceMemory {}; // OpenCL kernels OpenCLRunTime openclRunTime {}; KernelConfigurations kernelConfigurations {}; Kernels kernels {}; KernelRunTimeConfigurations kernelRunTimeConfigurations {}; // Timers Timers timers {}; // Observation AstroData::Observation observation; // Process command line arguments isa::utils::ArgumentList args(argc, argv); try { processCommandLineOptions(args, options, deviceOptions, dataOptions, kernelConfigurations, generatorOptions, observation); } catch ( std::exception & err ) { return 1; } // Load or generate input data try { try { hostMemory.zappedChannels.resize(observation.getNrChannels(deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int))); } catch ( std::out_of_range & err ) { std::cerr << "No padding specified for " << deviceOptions.deviceName << "." << std::endl; return 1; } try { AstroData::readZappedChannels(observation, dataOptions.channelsFile, hostMemory.zappedChannels); AstroData::readIntegrationSteps(observation, dataOptions.integrationFile, hostMemory.integrationSteps); } catch ( AstroData::FileError & err ) { std::cerr << err.what() << std::endl; return 1; } hostMemory.input.resize(observation.getNrBeams()); if ( dataOptions.dataLOFAR || dataOptions.dataSIGPROC || dataOptions.dataPSRDADA ) { loadInput(observation, deviceOptions, dataOptions, hostMemory, timers); } else { for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) { // TODO: if there are multiple synthesized beams, the generated data should take this into account hostMemory.input.at(beam) = new std::vector<std::vector<inputDataType> *>(observation.getNrBatches()); AstroData::generateSinglePulse(generatorOptions.width, generatorOptions.DM, observation, deviceOptions.padding.at(deviceOptions.deviceName), *(hostMemory.input.at(beam)), inputBits, generatorOptions.random); } } } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Print message with observation and search information if ( options.print) { std::cout << "Device: " << deviceOptions.deviceName << "(" + std::to_string(deviceOptions.platformID) + ", "; std::cout << std::to_string(deviceOptions.deviceID) + ")" << std::endl; std::cout << "Padding: " << deviceOptions.padding[deviceOptions.deviceName] << " bytes" << std::endl; std::cout << std::endl; std::cout << "Beams: " << observation.getNrBeams() << std::endl; std::cout << "Synthesized Beams: " << observation.getNrSynthesizedBeams() << std::endl; std::cout << "Batches: " << observation.getNrBatches() << std::endl; std::cout << "Samples: " << observation.getNrSamplesPerBatch() << std::endl; std::cout << "Sampling time: " << observation.getSamplingTime() << std::endl; std::cout << "Frequency range: " << observation.getMinFreq() << " MHz, " << observation.getMaxFreq() << " MHz"; std::cout << std::endl; std::cout << "Subbands: " << observation.getNrSubbands() << " (" << observation.getSubbandBandwidth() << " MHz)"; std::cout << std::endl; std::cout << "Channels: " << observation.getNrChannels() << " (" << observation.getChannelBandwidth() << " MHz)"; std::cout << std::endl; std::cout << "Zapped Channels: " << observation.getNrZappedChannels() << std::endl; std::cout << "Integration steps: " << hostMemory.integrationSteps.size() << std::endl; if ( options.subbandDedispersion ) { std::cout << "Subbanding DMs: " << observation.getNrDMs(true) << " (" << observation.getFirstDM(true) << ", "; std::cout << observation.getFirstDM(true) + ((observation.getNrDMs(true) - 1) * observation.getDMStep(true)); std::cout << ")" << std::endl; } std::cout << "DMs: " << observation.getNrDMs() << " (" << observation.getFirstDM() << ", "; std::cout << observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()) << ")"; std::cout << std::endl; std::cout << std::endl; } // Initialize OpenCL openclRunTime.context = new cl::Context(); openclRunTime.platforms = new std::vector<cl::Platform>(); openclRunTime.devices = new std::vector<cl::Device>(); openclRunTime.queues = new std::vector<std::vector<cl::CommandQueue>>(); try { isa::OpenCL::initializeOpenCL(deviceOptions.platformID, 1, openclRunTime.platforms, openclRunTime.context, openclRunTime.devices, openclRunTime.queues); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; return 1; } // Memory allocation allocateHostMemory(observation, options, deviceOptions, dataOptions, kernelConfigurations, hostMemory); if ( observation.getNrDelayBatches() > observation.getNrBatches() ) { std::cerr << "Not enough input batches for the specified search." << std::endl; return 1; } try { allocateDeviceMemory(openclRunTime, options, deviceOptions, hostMemory, deviceMemory); } catch ( cl::Error & err ) { std::cerr << "Memory error: " << err.what() << " " << err.err() << std::endl; return 1; } // Generate OpenCL kernels try { generateOpenCLKernels(openclRunTime, observation, options, deviceOptions, kernelConfigurations, hostMemory, deviceMemory, kernels); } catch ( std::exception & err ) { std::cerr << "OpenCL code generation error: " << err.what() << std::endl; return 1; } // Generate run time configurations for the OpenCL kernels generateOpenCLRunTimeConfigurations(observation, options, deviceOptions, kernelConfigurations, hostMemory, kernelRunTimeConfigurations); // Search loop pipeline(openclRunTime, observation, options, deviceOptions, dataOptions, timers, kernels, kernelConfigurations, kernelRunTimeConfigurations, hostMemory, deviceMemory); // Store performance statistics before shutting down std::ofstream outputStats; outputStats.open(dataOptions.outputFile + ".stats"); outputStats << std::fixed << std::setprecision(6); outputStats << "# nrDMs" << std::endl; if ( options.subbandDedispersion ) { outputStats << observation.getNrDMs(true) * observation.getNrDMs() << std::endl; } else { outputStats << observation.getNrDMs() << std::endl; } outputStats << "# timers.inputLoad" << std::endl; outputStats << timers.inputLoad.getTotalTime() << std::endl; outputStats << "# timers.search" << std::endl; outputStats << timers.search.getTotalTime() << std::endl; outputStats << "# inputHandlingTotal inputHandlingAvg err" << std::endl; outputStats << timers.inputHandling.getTotalTime() << " " << timers.inputHandling.getAverageTime() << " "; outputStats << timers.inputHandling.getStandardDeviation() << std::endl; outputStats << "# inputCopyTotal inputCopyAvg err" << std::endl; outputStats << timers.inputCopy.getTotalTime() << " " << timers.inputCopy.getAverageTime() << " "; outputStats << timers.inputCopy.getStandardDeviation() << std::endl; if ( ! options.subbandDedispersion ) { outputStats << "# dedispersionSingleStepTotal dedispersionSingleStepAvg err" << std::endl; outputStats << timers.dedispersionSingleStep.getTotalTime() << " "; outputStats << timers.dedispersionSingleStep.getAverageTime() << " "; outputStats << timers.dedispersionSingleStep.getStandardDeviation() << std::endl; } else { outputStats << "# dedispersionStepOneTotal dedispersionStepOneAvg err" << std::endl; outputStats << timers.dedispersionStepOne.getTotalTime() << " "; outputStats << timers.dedispersionStepOne.getAverageTime() << " "; outputStats << timers.dedispersionStepOne.getStandardDeviation() << std::endl; outputStats << "# dedispersionStepTwoTotal dedispersionStepTwoAvg err" << std::endl; outputStats << timers.dedispersionStepTwo.getTotalTime() << " "; outputStats << timers.dedispersionStepTwo.getAverageTime() << " "; outputStats << timers.dedispersionStepTwo.getStandardDeviation() << std::endl; } outputStats << "# integrationTotal integrationAvg err" << std::endl; outputStats << timers.integration.getTotalTime() << " " << timers.integration.getAverageTime() << " "; outputStats << timers.integration.getStandardDeviation() << std::endl; outputStats << "# snrTotal snrAvg err" << std::endl; outputStats << timers.snr.getTotalTime() << " " << timers.snr.getAverageTime() << " "; outputStats << timers.snr.getStandardDeviation() << std::endl; outputStats << "# outputCopyTotal outputCopyAvg err" << std::endl; outputStats << timers.outputCopy.getTotalTime() << " " << timers.outputCopy.getAverageTime() << " "; outputStats << timers.outputCopy.getStandardDeviation() << std::endl; outputStats << "# triggerTimeTotal triggerTimeAvg err" << std::endl; outputStats << timers.trigger.getTotalTime() << " " << timers.trigger.getAverageTime() << " "; outputStats << timers.trigger.getStandardDeviation() << std::endl; outputStats.close(); return 0; } <commit_msg>Missing space in output.<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON) // Copyright 2017 Netherlands eScience Center // // 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 <configuration.hpp> #include <CommandLine.hpp> #include <Kernels.hpp> #include <Memory.hpp> #include <Pipeline.hpp> int main(int argc, char * argv[]) { // Command line options Options options {}; DeviceOptions deviceOptions {}; DataOptions dataOptions {}; GeneratorOptions generatorOptions {}; // Memory HostMemory hostMemory {}; DeviceMemory deviceMemory {}; // OpenCL kernels OpenCLRunTime openclRunTime {}; KernelConfigurations kernelConfigurations {}; Kernels kernels {}; KernelRunTimeConfigurations kernelRunTimeConfigurations {}; // Timers Timers timers {}; // Observation AstroData::Observation observation; // Process command line arguments isa::utils::ArgumentList args(argc, argv); try { processCommandLineOptions(args, options, deviceOptions, dataOptions, kernelConfigurations, generatorOptions, observation); } catch ( std::exception & err ) { return 1; } // Load or generate input data try { try { hostMemory.zappedChannels.resize(observation.getNrChannels(deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int))); } catch ( std::out_of_range & err ) { std::cerr << "No padding specified for " << deviceOptions.deviceName << "." << std::endl; return 1; } try { AstroData::readZappedChannels(observation, dataOptions.channelsFile, hostMemory.zappedChannels); AstroData::readIntegrationSteps(observation, dataOptions.integrationFile, hostMemory.integrationSteps); } catch ( AstroData::FileError & err ) { std::cerr << err.what() << std::endl; return 1; } hostMemory.input.resize(observation.getNrBeams()); if ( dataOptions.dataLOFAR || dataOptions.dataSIGPROC || dataOptions.dataPSRDADA ) { loadInput(observation, deviceOptions, dataOptions, hostMemory, timers); } else { for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) { // TODO: if there are multiple synthesized beams, the generated data should take this into account hostMemory.input.at(beam) = new std::vector<std::vector<inputDataType> *>(observation.getNrBatches()); AstroData::generateSinglePulse(generatorOptions.width, generatorOptions.DM, observation, deviceOptions.padding.at(deviceOptions.deviceName), *(hostMemory.input.at(beam)), inputBits, generatorOptions.random); } } } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Print message with observation and search information if ( options.print) { std::cout << "Device: " << deviceOptions.deviceName << " (" + std::to_string(deviceOptions.platformID) + ", "; std::cout << std::to_string(deviceOptions.deviceID) + ")" << std::endl; std::cout << "Padding: " << deviceOptions.padding[deviceOptions.deviceName] << " bytes" << std::endl; std::cout << std::endl; std::cout << "Beams: " << observation.getNrBeams() << std::endl; std::cout << "Synthesized Beams: " << observation.getNrSynthesizedBeams() << std::endl; std::cout << "Batches: " << observation.getNrBatches() << std::endl; std::cout << "Samples: " << observation.getNrSamplesPerBatch() << std::endl; std::cout << "Sampling time: " << observation.getSamplingTime() << std::endl; std::cout << "Frequency range: " << observation.getMinFreq() << " MHz, " << observation.getMaxFreq() << " MHz"; std::cout << std::endl; std::cout << "Subbands: " << observation.getNrSubbands() << " (" << observation.getSubbandBandwidth() << " MHz)"; std::cout << std::endl; std::cout << "Channels: " << observation.getNrChannels() << " (" << observation.getChannelBandwidth() << " MHz)"; std::cout << std::endl; std::cout << "Zapped Channels: " << observation.getNrZappedChannels() << std::endl; std::cout << "Integration steps: " << hostMemory.integrationSteps.size() << std::endl; if ( options.subbandDedispersion ) { std::cout << "Subbanding DMs: " << observation.getNrDMs(true) << " (" << observation.getFirstDM(true) << ", "; std::cout << observation.getFirstDM(true) + ((observation.getNrDMs(true) - 1) * observation.getDMStep(true)); std::cout << ")" << std::endl; } std::cout << "DMs: " << observation.getNrDMs() << " (" << observation.getFirstDM() << ", "; std::cout << observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()) << ")"; std::cout << std::endl; std::cout << std::endl; } // Initialize OpenCL openclRunTime.context = new cl::Context(); openclRunTime.platforms = new std::vector<cl::Platform>(); openclRunTime.devices = new std::vector<cl::Device>(); openclRunTime.queues = new std::vector<std::vector<cl::CommandQueue>>(); try { isa::OpenCL::initializeOpenCL(deviceOptions.platformID, 1, openclRunTime.platforms, openclRunTime.context, openclRunTime.devices, openclRunTime.queues); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; return 1; } // Memory allocation allocateHostMemory(observation, options, deviceOptions, dataOptions, kernelConfigurations, hostMemory); if ( observation.getNrDelayBatches() > observation.getNrBatches() ) { std::cerr << "Not enough input batches for the specified search." << std::endl; return 1; } try { allocateDeviceMemory(openclRunTime, options, deviceOptions, hostMemory, deviceMemory); } catch ( cl::Error & err ) { std::cerr << "Memory error: " << err.what() << " " << err.err() << std::endl; return 1; } // Generate OpenCL kernels try { generateOpenCLKernels(openclRunTime, observation, options, deviceOptions, kernelConfigurations, hostMemory, deviceMemory, kernels); } catch ( std::exception & err ) { std::cerr << "OpenCL code generation error: " << err.what() << std::endl; return 1; } // Generate run time configurations for the OpenCL kernels generateOpenCLRunTimeConfigurations(observation, options, deviceOptions, kernelConfigurations, hostMemory, kernelRunTimeConfigurations); // Search loop pipeline(openclRunTime, observation, options, deviceOptions, dataOptions, timers, kernels, kernelConfigurations, kernelRunTimeConfigurations, hostMemory, deviceMemory); // Store performance statistics before shutting down std::ofstream outputStats; outputStats.open(dataOptions.outputFile + ".stats"); outputStats << std::fixed << std::setprecision(6); outputStats << "# nrDMs" << std::endl; if ( options.subbandDedispersion ) { outputStats << observation.getNrDMs(true) * observation.getNrDMs() << std::endl; } else { outputStats << observation.getNrDMs() << std::endl; } outputStats << "# timers.inputLoad" << std::endl; outputStats << timers.inputLoad.getTotalTime() << std::endl; outputStats << "# timers.search" << std::endl; outputStats << timers.search.getTotalTime() << std::endl; outputStats << "# inputHandlingTotal inputHandlingAvg err" << std::endl; outputStats << timers.inputHandling.getTotalTime() << " " << timers.inputHandling.getAverageTime() << " "; outputStats << timers.inputHandling.getStandardDeviation() << std::endl; outputStats << "# inputCopyTotal inputCopyAvg err" << std::endl; outputStats << timers.inputCopy.getTotalTime() << " " << timers.inputCopy.getAverageTime() << " "; outputStats << timers.inputCopy.getStandardDeviation() << std::endl; if ( ! options.subbandDedispersion ) { outputStats << "# dedispersionSingleStepTotal dedispersionSingleStepAvg err" << std::endl; outputStats << timers.dedispersionSingleStep.getTotalTime() << " "; outputStats << timers.dedispersionSingleStep.getAverageTime() << " "; outputStats << timers.dedispersionSingleStep.getStandardDeviation() << std::endl; } else { outputStats << "# dedispersionStepOneTotal dedispersionStepOneAvg err" << std::endl; outputStats << timers.dedispersionStepOne.getTotalTime() << " "; outputStats << timers.dedispersionStepOne.getAverageTime() << " "; outputStats << timers.dedispersionStepOne.getStandardDeviation() << std::endl; outputStats << "# dedispersionStepTwoTotal dedispersionStepTwoAvg err" << std::endl; outputStats << timers.dedispersionStepTwo.getTotalTime() << " "; outputStats << timers.dedispersionStepTwo.getAverageTime() << " "; outputStats << timers.dedispersionStepTwo.getStandardDeviation() << std::endl; } outputStats << "# integrationTotal integrationAvg err" << std::endl; outputStats << timers.integration.getTotalTime() << " " << timers.integration.getAverageTime() << " "; outputStats << timers.integration.getStandardDeviation() << std::endl; outputStats << "# snrTotal snrAvg err" << std::endl; outputStats << timers.snr.getTotalTime() << " " << timers.snr.getAverageTime() << " "; outputStats << timers.snr.getStandardDeviation() << std::endl; outputStats << "# outputCopyTotal outputCopyAvg err" << std::endl; outputStats << timers.outputCopy.getTotalTime() << " " << timers.outputCopy.getAverageTime() << " "; outputStats << timers.outputCopy.getStandardDeviation() << std::endl; outputStats << "# triggerTimeTotal triggerTimeAvg err" << std::endl; outputStats << timers.trigger.getTotalTime() << " " << timers.trigger.getAverageTime() << " "; outputStats << timers.trigger.getStandardDeviation() << std::endl; outputStats.close(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2017 offa // Copyright 2011 Ciaran McHale. // // 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's //-------- #include <stdio.h> #include <string.h> #include <stdlib.h> #include "Config2Cpp.h" #include "danek/Configuration.h" #include "danek/SchemaValidator.h" using namespace danek; void calculateRuleForName(const Configuration* cfg, const char* name, const char* uName, const StringVector& wildcardedNamesAndTypes, StringBuffer& rule) { rule.clear(); int len = wildcardedNamesAndTypes.size(); for (int i = 0; i < len; i += 3) { const char* keyword = wildcardedNamesAndTypes[i + 0].c_str(); // @optional or @required const char* wildcardedName = wildcardedNamesAndTypes[i + 1].c_str(); const char* type = wildcardedNamesAndTypes[i + 2].c_str(); if (Configuration::patternMatch(uName, wildcardedName)) { rule << keyword << " " << uName << " = " << type; return; } } //-------- // We couldn's determine the type from the wildcarded_names_and_types // table. So we fall back to using heuristics to guess a good type. //-------- if (cfg->type("", name) == ConfType::Scope) { rule << uName << " = scope"; } else if (cfg->type("", name) == ConfType::List) { rule << uName << " = list[string]"; } else { const char* str = cfg->lookupString("", name); if (cfg->isBoolean(str)) { rule << uName << " = boolean"; } else if (cfg->isInt(str)) { rule << uName << " = int"; } else if (cfg->isFloat(str)) { rule << uName << " = float"; } else if (cfg->isDurationSeconds(str)) { rule << uName << " = durationSeconds"; } else if (cfg->isDurationMilliseconds(str)) { rule << uName << " = durationMilliseconds"; } else if (cfg->isDurationMicroseconds(str)) { rule << uName << " = durationMicroseconds"; } else if (cfg->isMemorySizeBytes(str)) { rule << uName << " = memorySizeBytes"; } else if (cfg->isMemorySizeKB(str)) { rule << uName << " = memorySizeKB"; } else if (cfg->isMemorySizeMB(str)) { rule << uName << " = memorySizeMB"; } else { rule << uName << " = string"; } } } bool doesVectorcontainString(const StringVector& vec, const char* str) { int i; int len; len = vec.size(); for (i = 0; i < len; i++) { if (strcmp(vec[i].c_str(), str) == 0) { return true; } } return false; } void calculateSchema(const Configuration* cfg, const StringVector& namesList, const StringVector& recipeUserTypes, const StringVector& wildcardedNamesAndTypes, const StringVector& recipeIgnoreRules, StringVector& schema) throw(ConfigurationException) { StringBuffer rule; StringBuffer buf; StringVector uidNames; schema.clear(); for( const auto& str : recipeIgnoreRules ) { schema.push_back(str); } for( const auto& str : recipeUserTypes ) { schema.push_back(str); } int len = namesList.size(); for (int i = 0; i < len; i++) { const char* name = namesList[i].c_str(); if (strstr(name, "uid-") == nullptr) { calculateRuleForName(cfg, name, name, wildcardedNamesAndTypes, rule); schema.push_back(rule.str()); } else { const char* uName = cfg->unexpandUid(name, buf); if (!doesVectorcontainString(uidNames, uName)) { uidNames.push_back(uName); calculateRuleForName(cfg, name, uName, wildcardedNamesAndTypes, rule); schema.push_back(rule.str()); } } } } bool doesPatternMatchAnyUnexpandedNameInList( const Configuration* cfg, const char* pattern, const StringVector& namesList) { StringBuffer buf; int len = namesList.size(); for (int i = 0; i < len; i++) { const char* uName = cfg->unexpandUid(namesList[i].c_str(), buf); if (Configuration::patternMatch(uName, pattern)) { return true; } } return false; } void checkForUnmatchedPatterns(const Configuration* cfg, const StringVector& namesList, const StringVector& wildcardedNamesAndTypes, StringVector& unmatchedPatterns) throw(ConfigurationException) { unmatchedPatterns.clear(); //-------- // Check if there is a wildcarded name that does not match anything //-------- int len = wildcardedNamesAndTypes.size(); for (int i = 0; i < len; i += 3) { const char* wildcardedName = wildcardedNamesAndTypes[i + 1].c_str(); if (!doesPatternMatchAnyUnexpandedNameInList(cfg, wildcardedName, namesList)) { unmatchedPatterns.push_back(wildcardedName); } } } //---------------------------------------------------------------------- // File: main() // // Description: Mainline of "config2cpp" //---------------------------------------------------------------------- int main(int argc, char** argv) { Config2Cpp util("config2cpp"); StringVector namesList; StringVector recipeUserTypes; StringVector wildcardedNamesAndTypes; StringVector recipeIgnoreRules; StringVector unmatchedPatterns; StringVector schema; SchemaValidator sv; bool ok = util.parseCmdLineArgs(argc, argv); Configuration* cfg = Configuration::create(); Configuration* schemaCfg = Configuration::create(); if (ok && util.wantSchema()) { try { cfg->parse(util.cfgFileName()); cfg->listFullyScopedNames("", "", ConfType::ScopesAndVars, true, namesList); if (util.schemaOverrideCfg() != nullptr) { const char* overrideSchema[] = { "@typedef keyword = enum[\"@optional\", \"@required\"]", "user_types = list[string]", "wildcarded_names_and_types = table[keyword,keyword, " "string,wildcarded-name, string,type]", "ignore_rules = list[string]", nullptr // null-terminated array }; schemaCfg->parse(util.schemaOverrideCfg()); const char* scope = util.schemaOverrideScope(); sv.parseSchema(overrideSchema); sv.validate(schemaCfg, scope, ""); schemaCfg->lookupList(scope, "user_types", recipeUserTypes); schemaCfg->lookupList(scope, "wildcarded_names_and_types", wildcardedNamesAndTypes); schemaCfg->lookupList(scope, "ignore_rules", recipeIgnoreRules); } calculateSchema( cfg, namesList, recipeUserTypes, wildcardedNamesAndTypes, recipeIgnoreRules, schema); checkForUnmatchedPatterns(cfg, namesList, wildcardedNamesAndTypes, unmatchedPatterns); } catch (const ConfigurationException& ex) { fprintf(stderr, "%s\n", ex.c_str()); ok = false; } int len = unmatchedPatterns.size(); if (len != 0) { fprintf(stderr, "%s %s\n", "Error: the following patterns in the schema", "recipe did not match anything"); for (int i = 0; i < len; i++) { fprintf(stderr, "\t'%s'\n", unmatchedPatterns[i].c_str()); } ok = false; } } if (ok) { const auto data = schema.get(); std::vector<const char*> buffer; // Deprecated conversion; kept for compatibility for( const auto& str : data ) { buffer.push_back(&str.front()); } ok = util.generateFiles(buffer.data(), buffer.size()); } cfg->destroy(); if (ok) { return 0; } else { return 1; } } <commit_msg>Exception specification removed.<commit_after>// Copyright (c) 2017 offa // Copyright 2011 Ciaran McHale. // // 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's //-------- #include <stdio.h> #include <string.h> #include <stdlib.h> #include "Config2Cpp.h" #include "danek/Configuration.h" #include "danek/SchemaValidator.h" using namespace danek; void calculateRuleForName(const Configuration* cfg, const char* name, const char* uName, const StringVector& wildcardedNamesAndTypes, StringBuffer& rule) { rule.clear(); int len = wildcardedNamesAndTypes.size(); for (int i = 0; i < len; i += 3) { const char* keyword = wildcardedNamesAndTypes[i + 0].c_str(); // @optional or @required const char* wildcardedName = wildcardedNamesAndTypes[i + 1].c_str(); const char* type = wildcardedNamesAndTypes[i + 2].c_str(); if (Configuration::patternMatch(uName, wildcardedName)) { rule << keyword << " " << uName << " = " << type; return; } } //-------- // We couldn's determine the type from the wildcarded_names_and_types // table. So we fall back to using heuristics to guess a good type. //-------- if (cfg->type("", name) == ConfType::Scope) { rule << uName << " = scope"; } else if (cfg->type("", name) == ConfType::List) { rule << uName << " = list[string]"; } else { const char* str = cfg->lookupString("", name); if (cfg->isBoolean(str)) { rule << uName << " = boolean"; } else if (cfg->isInt(str)) { rule << uName << " = int"; } else if (cfg->isFloat(str)) { rule << uName << " = float"; } else if (cfg->isDurationSeconds(str)) { rule << uName << " = durationSeconds"; } else if (cfg->isDurationMilliseconds(str)) { rule << uName << " = durationMilliseconds"; } else if (cfg->isDurationMicroseconds(str)) { rule << uName << " = durationMicroseconds"; } else if (cfg->isMemorySizeBytes(str)) { rule << uName << " = memorySizeBytes"; } else if (cfg->isMemorySizeKB(str)) { rule << uName << " = memorySizeKB"; } else if (cfg->isMemorySizeMB(str)) { rule << uName << " = memorySizeMB"; } else { rule << uName << " = string"; } } } bool doesVectorcontainString(const StringVector& vec, const char* str) { int i; int len; len = vec.size(); for (i = 0; i < len; i++) { if (strcmp(vec[i].c_str(), str) == 0) { return true; } } return false; } void calculateSchema(const Configuration* cfg, const StringVector& namesList, const StringVector& recipeUserTypes, const StringVector& wildcardedNamesAndTypes, const StringVector& recipeIgnoreRules, StringVector& schema) { StringBuffer rule; StringBuffer buf; StringVector uidNames; schema.clear(); for( const auto& str : recipeIgnoreRules ) { schema.push_back(str); } for( const auto& str : recipeUserTypes ) { schema.push_back(str); } int len = namesList.size(); for (int i = 0; i < len; i++) { const char* name = namesList[i].c_str(); if (strstr(name, "uid-") == nullptr) { calculateRuleForName(cfg, name, name, wildcardedNamesAndTypes, rule); schema.push_back(rule.str()); } else { const char* uName = cfg->unexpandUid(name, buf); if (!doesVectorcontainString(uidNames, uName)) { uidNames.push_back(uName); calculateRuleForName(cfg, name, uName, wildcardedNamesAndTypes, rule); schema.push_back(rule.str()); } } } } bool doesPatternMatchAnyUnexpandedNameInList( const Configuration* cfg, const char* pattern, const StringVector& namesList) { StringBuffer buf; int len = namesList.size(); for (int i = 0; i < len; i++) { const char* uName = cfg->unexpandUid(namesList[i].c_str(), buf); if (Configuration::patternMatch(uName, pattern)) { return true; } } return false; } void checkForUnmatchedPatterns(const Configuration* cfg, const StringVector& namesList, const StringVector& wildcardedNamesAndTypes, StringVector& unmatchedPatterns) { unmatchedPatterns.clear(); //-------- // Check if there is a wildcarded name that does not match anything //-------- int len = wildcardedNamesAndTypes.size(); for (int i = 0; i < len; i += 3) { const char* wildcardedName = wildcardedNamesAndTypes[i + 1].c_str(); if (!doesPatternMatchAnyUnexpandedNameInList(cfg, wildcardedName, namesList)) { unmatchedPatterns.push_back(wildcardedName); } } } //---------------------------------------------------------------------- // File: main() // // Description: Mainline of "config2cpp" //---------------------------------------------------------------------- int main(int argc, char** argv) { Config2Cpp util("config2cpp"); StringVector namesList; StringVector recipeUserTypes; StringVector wildcardedNamesAndTypes; StringVector recipeIgnoreRules; StringVector unmatchedPatterns; StringVector schema; SchemaValidator sv; bool ok = util.parseCmdLineArgs(argc, argv); Configuration* cfg = Configuration::create(); Configuration* schemaCfg = Configuration::create(); if (ok && util.wantSchema()) { try { cfg->parse(util.cfgFileName()); cfg->listFullyScopedNames("", "", ConfType::ScopesAndVars, true, namesList); if (util.schemaOverrideCfg() != nullptr) { const char* overrideSchema[] = { "@typedef keyword = enum[\"@optional\", \"@required\"]", "user_types = list[string]", "wildcarded_names_and_types = table[keyword,keyword, " "string,wildcarded-name, string,type]", "ignore_rules = list[string]", nullptr // null-terminated array }; schemaCfg->parse(util.schemaOverrideCfg()); const char* scope = util.schemaOverrideScope(); sv.parseSchema(overrideSchema); sv.validate(schemaCfg, scope, ""); schemaCfg->lookupList(scope, "user_types", recipeUserTypes); schemaCfg->lookupList(scope, "wildcarded_names_and_types", wildcardedNamesAndTypes); schemaCfg->lookupList(scope, "ignore_rules", recipeIgnoreRules); } calculateSchema( cfg, namesList, recipeUserTypes, wildcardedNamesAndTypes, recipeIgnoreRules, schema); checkForUnmatchedPatterns(cfg, namesList, wildcardedNamesAndTypes, unmatchedPatterns); } catch (const ConfigurationException& ex) { fprintf(stderr, "%s\n", ex.c_str()); ok = false; } int len = unmatchedPatterns.size(); if (len != 0) { fprintf(stderr, "%s %s\n", "Error: the following patterns in the schema", "recipe did not match anything"); for (int i = 0; i < len; i++) { fprintf(stderr, "\t'%s'\n", unmatchedPatterns[i].c_str()); } ok = false; } } if (ok) { const auto data = schema.get(); std::vector<const char*> buffer; // Deprecated conversion; kept for compatibility for( const auto& str : data ) { buffer.push_back(&str.front()); } ok = util.generateFiles(buffer.data(), buffer.size()); } cfg->destroy(); if (ok) { return 0; } else { return 1; } } <|endoftext|>
<commit_before>#define BOOST_TEST_STATIC_LINK #include <boost/test/unit_test.hpp> #include <string> #include <limits> #include <stdexcept> #include "./../../fixed_point_lib/src/number.hpp" namespace utils { namespace unit_tests { namespace { using utils::SOU_number; using utils::UOU_number; } BOOST_AUTO_TEST_SUITE(Range) // FIXED-POINT RANGE TESTS ////////////////////////////////////////////////////////////////////////// /// idea of test 'rangeFitBuiltinCheck': /// checks if range of fixed-point of word length 8,16,32,64 is the same /// as for built-in integers BOOST_AUTO_TEST_CASE(rangeFitBultinCheck) { typedef SOU_number<7, 6>::type type1; typedef UOU_number<16, 23>::type type2; typedef UOU_number<32, 12>::type type3; typedef UOU_number<64, 54>::type type4; typedef SOU_number<15, 12>::type type5; std::string const message("fixed-point has wrong range"); typedef boost::int_t<8>::exact bit8_stype; BOOST_CHECK_MESSAGE(std::numeric_limits<bit8_stype>::max() == type1::bounds::max, message); BOOST_CHECK_MESSAGE(std::numeric_limits<bit8_stype>::min() == type1::bounds::min, message); typedef boost::uint_t<16>::exact bit16_utype; BOOST_CHECK_MESSAGE(std::numeric_limits<bit16_utype>::max() == type2::bounds::max, message); BOOST_CHECK_MESSAGE(std::numeric_limits<bit16_utype>::min() == type2::bounds::min, message); typedef boost::uint_t<32>::exact bit32_utype; BOOST_CHECK_MESSAGE(std::numeric_limits<bit32_utype>::max() == type3::bounds::max, message); BOOST_CHECK_MESSAGE(std::numeric_limits<bit32_utype>::min() == type3::bounds::min, message); typedef boost::uint_t<64>::exact bit64_utype; BOOST_CHECK_MESSAGE(std::numeric_limits<bit64_utype>::max() == type4::bounds::max, message); BOOST_CHECK_MESSAGE(std::numeric_limits<bit64_utype>::min() == type4::bounds::min, message); typedef boost::int_t<16>::exact bit16_stype; BOOST_CHECK_MESSAGE(std::numeric_limits<bit16_stype>::max() == type5::bounds::max, message); BOOST_CHECK_MESSAGE(std::numeric_limits<bit16_stype>::min() == type5::bounds::min, message); } /// idea of test 'outOfRangeCheck': /// common checks if integer value (interpreted as fixed-point) is out /// of range BOOST_AUTO_TEST_CASE(outOfRangeCheck) { typedef SOU_number<8, 13>::type type1; typedef UOU_number<13, 1>::type type2; std::string const message("Positive overflow was not detected"); try { type1(300u); BOOST_FAIL(message); } catch (std::overflow_error e){} try { type2(10000u); BOOST_FAIL(message); } catch (std::overflow_error e){} } BOOST_AUTO_TEST_SUITE_END() }} <commit_msg>range_cases.cpp: refactoring due to changes in fixed_point.hpp<commit_after>#define BOOST_TEST_STATIC_LINK #include <boost/test/unit_test.hpp> #include <string> #include <limits> #include <stdexcept> #include "./../../fixed_point_lib/src/fixed_point.hpp" namespace core { namespace unit_tests { namespace { using core::SOU_fixed_point; using core::UOU_fixed_point; } BOOST_AUTO_TEST_SUITE(Range) // FIXED-POINT RANGE TESTS ////////////////////////////////////////////////////////////////////////// /// idea of test 'rangeFitBuiltinCheck': /// checks if range of fixed-point of word length 8,16,32,64 is the same /// as for built-in integers BOOST_AUTO_TEST_CASE(rangeFitBultinCheck) { typedef SOU_fixed_point<7, 6>::type type1; typedef UOU_fixed_point<16, 23>::type type2; typedef UOU_fixed_point<32, 12>::type type3; typedef UOU_fixed_point<64, 54>::type type4; typedef SOU_fixed_point<15, 12>::type type5; std::string const message("fixed-point has wrong range"); typedef boost::int_t<8>::exact bit8_stype; BOOST_CHECK_MESSAGE(std::numeric_limits<bit8_stype>::max() == type1::bounds::max, message); BOOST_CHECK_MESSAGE(std::numeric_limits<bit8_stype>::min() == type1::bounds::min, message); typedef boost::uint_t<16>::exact bit16_utype; BOOST_CHECK_MESSAGE(std::numeric_limits<bit16_utype>::max() == type2::bounds::max, message); BOOST_CHECK_MESSAGE(std::numeric_limits<bit16_utype>::min() == type2::bounds::min, message); typedef boost::uint_t<32>::exact bit32_utype; BOOST_CHECK_MESSAGE(std::numeric_limits<bit32_utype>::max() == type3::bounds::max, message); BOOST_CHECK_MESSAGE(std::numeric_limits<bit32_utype>::min() == type3::bounds::min, message); typedef boost::uint_t<64>::exact bit64_utype; BOOST_CHECK_MESSAGE(std::numeric_limits<bit64_utype>::max() == type4::bounds::max, message); BOOST_CHECK_MESSAGE(std::numeric_limits<bit64_utype>::min() == type4::bounds::min, message); typedef boost::int_t<16>::exact bit16_stype; BOOST_CHECK_MESSAGE(std::numeric_limits<bit16_stype>::max() == type5::bounds::max, message); BOOST_CHECK_MESSAGE(std::numeric_limits<bit16_stype>::min() == type5::bounds::min, message); } /// idea of test 'outOfRangeCheck': /// common checks if integer value (interpreted as fixed-point) is out /// of range BOOST_AUTO_TEST_CASE(outOfRangeCheck) { typedef SOU_fixed_point<8, 13>::type type1; typedef UOU_fixed_point<13, 1>::type type2; std::string const message("Positive overflow was not detected"); try { type1(300u); BOOST_FAIL(message); } catch (std::overflow_error e){} try { type2(10000u); BOOST_FAIL(message); } catch (std::overflow_error e){} } BOOST_AUTO_TEST_SUITE_END() }} <|endoftext|>
<commit_before>// Interface for 2D Canvas element // // Copyright (C) 2012 Thomas Geymayer <tomgey@gmail.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA #include "CanvasElement.hxx" #include <simgear/canvas/Canvas.hxx> #include <simgear/canvas/CanvasEventListener.hxx> #include <simgear/canvas/CanvasEventVisitor.hxx> #include <simgear/canvas/MouseEvent.hxx> #include <osg/Drawable> #include <osg/Geode> #include <osg/Scissor> #include <boost/algorithm/string/predicate.hpp> #include <boost/foreach.hpp> #include <boost/lexical_cast.hpp> #include <boost/make_shared.hpp> #include <boost/tokenizer.hpp> #include <cassert> #include <cstring> namespace simgear { namespace canvas { const std::string NAME_TRANSFORM = "tf"; //---------------------------------------------------------------------------- void Element::removeListener() { _node->removeChangeListener(this); } //---------------------------------------------------------------------------- Element::~Element() { removeListener(); BOOST_FOREACH(osg::Group* parent, _transform->getParents()) { parent->removeChild(_transform); } } //---------------------------------------------------------------------------- ElementWeakPtr Element::getWeakPtr() const { return boost::static_pointer_cast<Element>(_self.lock()); } //---------------------------------------------------------------------------- void Element::update(double dt) { if( !_transform->getNodeMask() ) // Don't do anything if element is hidden return; if( _transform_dirty ) { osg::Matrix m; for( size_t i = 0; i < _transform_types.size(); ++i ) { // Skip unused indizes... if( _transform_types[i] == TT_NONE ) continue; SGPropertyNode* tf_node = _node->getChild("tf", i, true); // Build up the matrix representation of the current transform node osg::Matrix tf; switch( _transform_types[i] ) { case TT_MATRIX: tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1), tf_node->getDoubleValue("m[1]", 0), 0, tf_node->getDoubleValue("m[6]", 0), tf_node->getDoubleValue("m[2]", 0), tf_node->getDoubleValue("m[3]", 1), 0, tf_node->getDoubleValue("m[7]", 0), 0, 0, 1, 0, tf_node->getDoubleValue("m[4]", 0), tf_node->getDoubleValue("m[5]", 0), 0, tf_node->getDoubleValue("m[8]", 1) ); break; case TT_TRANSLATE: tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0), tf_node->getDoubleValue("t[1]", 0), 0 ) ); break; case TT_ROTATE: tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 ); break; case TT_SCALE: { float sx = tf_node->getDoubleValue("s[0]", 1); // sy defaults to sx... tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 ); break; } default: break; } m.postMult( tf ); } _transform->setMatrix(m); _transform_dirty = false; } } //---------------------------------------------------------------------------- naRef Element::addEventListener(const nasal::CallContext& ctx) { const std::string type_str = ctx.requireArg<std::string>(0); naRef code = ctx.requireArg<naRef>(1); SG_LOG ( SG_NASAL, SG_INFO, "addEventListener(" << _node->getPath() << ", " << type_str << ")" ); Event::Type type = Event::strToType(type_str); if( type == Event::UNKNOWN ) naRuntimeError( ctx.c, "addEventListener: Unknown event type %s", type_str.c_str() ); _listener[ type ].push_back ( boost::make_shared<EventListener>( code, _canvas.lock()->getSystemAdapter() ) ); return naNil(); } //---------------------------------------------------------------------------- bool Element::accept(EventVisitor& visitor) { return visitor.apply(*this); } //---------------------------------------------------------------------------- bool Element::ascend(EventVisitor& visitor) { if( _parent ) return _parent->accept(visitor); return true; } //---------------------------------------------------------------------------- bool Element::traverse(EventVisitor& visitor) { return true; } //---------------------------------------------------------------------------- void Element::callListeners(const canvas::EventPtr& event) { ListenerMap::iterator listeners = _listener.find(event->getType()); if( listeners == _listener.end() ) return; BOOST_FOREACH(EventListenerPtr listener, listeners->second) listener->call(event); } //---------------------------------------------------------------------------- bool Element::hitBound( const osg::Vec2f& pos, const osg::Vec2f& local_pos ) const { const osg::Vec3f pos3(pos, 0); // Drawables have a bounding box... if( _drawable ) { if( !_drawable->getBound().contains(osg::Vec3f(local_pos, 0)) ) return false; } // ... for other elements, i.e. groups only a bounding sphere is available else if( !_transform->getBound().contains(osg::Vec3f(pos, 0)) ) return false; return true; } //---------------------------------------------------------------------------- osg::ref_ptr<osg::MatrixTransform> Element::getMatrixTransform() { return _transform; } //---------------------------------------------------------------------------- void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child) { if( parent == _node && child->getNameString() == NAME_TRANSFORM ) { if( child->getIndex() >= static_cast<int>(_transform_types.size()) ) _transform_types.resize( child->getIndex() + 1 ); _transform_types[ child->getIndex() ] = TT_NONE; _transform_dirty = true; return; } else if( parent->getParent() == _node && parent->getNameString() == NAME_TRANSFORM ) { assert(parent->getIndex() < static_cast<int>(_transform_types.size())); const std::string& name = child->getNameString(); TransformType& type = _transform_types[parent->getIndex()]; if( name == "m" ) type = TT_MATRIX; else if( name == "t" ) type = TT_TRANSLATE; else if( name == "rot" ) type = TT_ROTATE; else if( name == "s" ) type = TT_SCALE; _transform_dirty = true; return; } childAdded(child); } //---------------------------------------------------------------------------- void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child) { if( parent == _node && child->getNameString() == NAME_TRANSFORM ) { if( child->getIndex() >= static_cast<int>(_transform_types.size()) ) { SG_LOG ( SG_GENERAL, SG_WARN, "Element::childRemoved: unknown transform: " << child->getPath() ); return; } _transform_types[ child->getIndex() ] = TT_NONE; while( !_transform_types.empty() && _transform_types.back() == TT_NONE ) _transform_types.pop_back(); _transform_dirty = true; return; } childRemoved(child); } //---------------------------------------------------------------------------- void Element::valueChanged(SGPropertyNode* child) { SGPropertyNode *parent = child->getParent(); if( parent == _node ) { if( setStyle(child) ) return; else if( child->getNameString() == "update" ) return update(0); else if( child->getNameString() == "visible" ) // TODO check if we need another nodemask return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 ); } else if( parent->getParent() == _node && parent->getNameString() == NAME_TRANSFORM ) { _transform_dirty = true; return; } childChanged(child); } //---------------------------------------------------------------------------- bool Element::setStyle(const SGPropertyNode* child) { StyleSetters::const_iterator setter = _style_setters.find(child->getNameString()); if( setter == _style_setters.end() ) return false; setter->second(child); return true; } //---------------------------------------------------------------------------- void Element::setClip(const std::string& clip) { if( clip.empty() || clip == "auto" ) { getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR); return; } // TODO generalize CSS property parsing const std::string RECT("rect("); if( !boost::ends_with(clip, ")") || !boost::starts_with(clip, RECT) ) { SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip); return; } typedef boost::tokenizer<boost::char_separator<char> > tokenizer; const boost::char_separator<char> del(", \t\npx"); tokenizer tokens(clip.begin() + RECT.size(), clip.end() - 1, del); int comp = 0; int values[4]; for( tokenizer::const_iterator tok = tokens.begin(); tok != tokens.end() && comp < 4; ++tok, ++comp ) { values[comp] = boost::lexical_cast<int>(*tok); } if( comp < 4 ) { SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip); return; } float scale_x = 1, scale_y = 1; CanvasPtr canvas = _canvas.lock(); if( canvas ) { // The scissor rectangle isn't affected by any transformation, so we need // to convert to image/canvas coordinates on our selves. scale_x = canvas->getSizeX() / static_cast<float>(canvas->getViewWidth()); scale_y = canvas->getSizeY() / static_cast<float>(canvas->getViewHeight()); } osg::Scissor* scissor = new osg::Scissor(); // <top>, <right>, <bottom>, <left> scissor->x() = scale_x * values[3]; scissor->y() = scale_y * values[0]; scissor->width() = scale_x * (values[1] - values[3]); scissor->height() = scale_y * (values[2] - values[0]); if( canvas ) // Canvas has y axis upside down scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height(); getOrCreateStateSet()->setAttributeAndModes(scissor); } //---------------------------------------------------------------------------- void Element::setBoundingBox(const osg::BoundingBox& bb) { if( _bounding_box.empty() ) { SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true); _bounding_box.resize(4); _bounding_box[0] = bb_node->getChild("min-x", 0, true); _bounding_box[1] = bb_node->getChild("min-y", 0, true); _bounding_box[2] = bb_node->getChild("max-x", 0, true); _bounding_box[3] = bb_node->getChild("max-y", 0, true); } _bounding_box[0]->setFloatValue(bb._min.x()); _bounding_box[1]->setFloatValue(bb._min.y()); _bounding_box[2]->setFloatValue(bb._max.x()); _bounding_box[3]->setFloatValue(bb._max.y()); } //---------------------------------------------------------------------------- osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const { return osg::BoundingBox(); } //---------------------------------------------------------------------------- Element::Element( const CanvasWeakPtr& canvas, const SGPropertyNode_ptr& node, const Style& parent_style, Element* parent ): PropertyBasedElement(node), _canvas( canvas ), _parent( parent ), _transform_dirty( false ), _transform( new osg::MatrixTransform ), _style( parent_style ), _drawable( 0 ) { SG_LOG ( SG_GL, SG_DEBUG, "New canvas element " << node->getPath() ); addStyle("clip", &Element::setClip, this); } //---------------------------------------------------------------------------- void Element::setDrawable( osg::Drawable* drawable ) { _drawable = drawable; assert( _drawable ); osg::ref_ptr<osg::Geode> geode = new osg::Geode; geode->addDrawable(_drawable); _transform->addChild(geode); } //---------------------------------------------------------------------------- osg::StateSet* Element::getOrCreateStateSet() { return _drawable ? _drawable->getOrCreateStateSet() : _transform->getOrCreateStateSet(); } //---------------------------------------------------------------------------- void Element::setupStyle() { BOOST_FOREACH( Style::value_type style, _style ) setStyle(style.second); } } // namespace canvas } // namespace simgear <commit_msg>Canvas: Provide sane default bounding box (For Image & Text)<commit_after>// Interface for 2D Canvas element // // Copyright (C) 2012 Thomas Geymayer <tomgey@gmail.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA #include "CanvasElement.hxx" #include <simgear/canvas/Canvas.hxx> #include <simgear/canvas/CanvasEventListener.hxx> #include <simgear/canvas/CanvasEventVisitor.hxx> #include <simgear/canvas/MouseEvent.hxx> #include <osg/Drawable> #include <osg/Geode> #include <osg/Scissor> #include <boost/algorithm/string/predicate.hpp> #include <boost/foreach.hpp> #include <boost/lexical_cast.hpp> #include <boost/make_shared.hpp> #include <boost/tokenizer.hpp> #include <cassert> #include <cstring> namespace simgear { namespace canvas { const std::string NAME_TRANSFORM = "tf"; //---------------------------------------------------------------------------- void Element::removeListener() { _node->removeChangeListener(this); } //---------------------------------------------------------------------------- Element::~Element() { removeListener(); BOOST_FOREACH(osg::Group* parent, _transform->getParents()) { parent->removeChild(_transform); } } //---------------------------------------------------------------------------- ElementWeakPtr Element::getWeakPtr() const { return boost::static_pointer_cast<Element>(_self.lock()); } //---------------------------------------------------------------------------- void Element::update(double dt) { if( !_transform->getNodeMask() ) // Don't do anything if element is hidden return; if( _transform_dirty ) { osg::Matrix m; for( size_t i = 0; i < _transform_types.size(); ++i ) { // Skip unused indizes... if( _transform_types[i] == TT_NONE ) continue; SGPropertyNode* tf_node = _node->getChild("tf", i, true); // Build up the matrix representation of the current transform node osg::Matrix tf; switch( _transform_types[i] ) { case TT_MATRIX: tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1), tf_node->getDoubleValue("m[1]", 0), 0, tf_node->getDoubleValue("m[6]", 0), tf_node->getDoubleValue("m[2]", 0), tf_node->getDoubleValue("m[3]", 1), 0, tf_node->getDoubleValue("m[7]", 0), 0, 0, 1, 0, tf_node->getDoubleValue("m[4]", 0), tf_node->getDoubleValue("m[5]", 0), 0, tf_node->getDoubleValue("m[8]", 1) ); break; case TT_TRANSLATE: tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0), tf_node->getDoubleValue("t[1]", 0), 0 ) ); break; case TT_ROTATE: tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 ); break; case TT_SCALE: { float sx = tf_node->getDoubleValue("s[0]", 1); // sy defaults to sx... tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 ); break; } default: break; } m.postMult( tf ); } _transform->setMatrix(m); _transform_dirty = false; } } //---------------------------------------------------------------------------- naRef Element::addEventListener(const nasal::CallContext& ctx) { const std::string type_str = ctx.requireArg<std::string>(0); naRef code = ctx.requireArg<naRef>(1); SG_LOG ( SG_NASAL, SG_INFO, "addEventListener(" << _node->getPath() << ", " << type_str << ")" ); Event::Type type = Event::strToType(type_str); if( type == Event::UNKNOWN ) naRuntimeError( ctx.c, "addEventListener: Unknown event type %s", type_str.c_str() ); _listener[ type ].push_back ( boost::make_shared<EventListener>( code, _canvas.lock()->getSystemAdapter() ) ); return naNil(); } //---------------------------------------------------------------------------- bool Element::accept(EventVisitor& visitor) { return visitor.apply(*this); } //---------------------------------------------------------------------------- bool Element::ascend(EventVisitor& visitor) { if( _parent ) return _parent->accept(visitor); return true; } //---------------------------------------------------------------------------- bool Element::traverse(EventVisitor& visitor) { return true; } //---------------------------------------------------------------------------- void Element::callListeners(const canvas::EventPtr& event) { ListenerMap::iterator listeners = _listener.find(event->getType()); if( listeners == _listener.end() ) return; BOOST_FOREACH(EventListenerPtr listener, listeners->second) listener->call(event); } //---------------------------------------------------------------------------- bool Element::hitBound( const osg::Vec2f& pos, const osg::Vec2f& local_pos ) const { const osg::Vec3f pos3(pos, 0); // Drawables have a bounding box... if( _drawable ) { if( !_drawable->getBound().contains(osg::Vec3f(local_pos, 0)) ) return false; } // ... for other elements, i.e. groups only a bounding sphere is available else if( !_transform->getBound().contains(osg::Vec3f(pos, 0)) ) return false; return true; } //---------------------------------------------------------------------------- osg::ref_ptr<osg::MatrixTransform> Element::getMatrixTransform() { return _transform; } //---------------------------------------------------------------------------- void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child) { if( parent == _node && child->getNameString() == NAME_TRANSFORM ) { if( child->getIndex() >= static_cast<int>(_transform_types.size()) ) _transform_types.resize( child->getIndex() + 1 ); _transform_types[ child->getIndex() ] = TT_NONE; _transform_dirty = true; return; } else if( parent->getParent() == _node && parent->getNameString() == NAME_TRANSFORM ) { assert(parent->getIndex() < static_cast<int>(_transform_types.size())); const std::string& name = child->getNameString(); TransformType& type = _transform_types[parent->getIndex()]; if( name == "m" ) type = TT_MATRIX; else if( name == "t" ) type = TT_TRANSLATE; else if( name == "rot" ) type = TT_ROTATE; else if( name == "s" ) type = TT_SCALE; _transform_dirty = true; return; } childAdded(child); } //---------------------------------------------------------------------------- void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child) { if( parent == _node && child->getNameString() == NAME_TRANSFORM ) { if( child->getIndex() >= static_cast<int>(_transform_types.size()) ) { SG_LOG ( SG_GENERAL, SG_WARN, "Element::childRemoved: unknown transform: " << child->getPath() ); return; } _transform_types[ child->getIndex() ] = TT_NONE; while( !_transform_types.empty() && _transform_types.back() == TT_NONE ) _transform_types.pop_back(); _transform_dirty = true; return; } childRemoved(child); } //---------------------------------------------------------------------------- void Element::valueChanged(SGPropertyNode* child) { SGPropertyNode *parent = child->getParent(); if( parent == _node ) { if( setStyle(child) ) return; else if( child->getNameString() == "update" ) return update(0); else if( child->getNameString() == "visible" ) // TODO check if we need another nodemask return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 ); } else if( parent->getParent() == _node && parent->getNameString() == NAME_TRANSFORM ) { _transform_dirty = true; return; } childChanged(child); } //---------------------------------------------------------------------------- bool Element::setStyle(const SGPropertyNode* child) { StyleSetters::const_iterator setter = _style_setters.find(child->getNameString()); if( setter == _style_setters.end() ) return false; setter->second(child); return true; } //---------------------------------------------------------------------------- void Element::setClip(const std::string& clip) { if( clip.empty() || clip == "auto" ) { getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR); return; } // TODO generalize CSS property parsing const std::string RECT("rect("); if( !boost::ends_with(clip, ")") || !boost::starts_with(clip, RECT) ) { SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip); return; } typedef boost::tokenizer<boost::char_separator<char> > tokenizer; const boost::char_separator<char> del(", \t\npx"); tokenizer tokens(clip.begin() + RECT.size(), clip.end() - 1, del); int comp = 0; int values[4]; for( tokenizer::const_iterator tok = tokens.begin(); tok != tokens.end() && comp < 4; ++tok, ++comp ) { values[comp] = boost::lexical_cast<int>(*tok); } if( comp < 4 ) { SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip); return; } float scale_x = 1, scale_y = 1; CanvasPtr canvas = _canvas.lock(); if( canvas ) { // The scissor rectangle isn't affected by any transformation, so we need // to convert to image/canvas coordinates on our selves. scale_x = canvas->getSizeX() / static_cast<float>(canvas->getViewWidth()); scale_y = canvas->getSizeY() / static_cast<float>(canvas->getViewHeight()); } osg::Scissor* scissor = new osg::Scissor(); // <top>, <right>, <bottom>, <left> scissor->x() = scale_x * values[3]; scissor->y() = scale_y * values[0]; scissor->width() = scale_x * (values[1] - values[3]); scissor->height() = scale_y * (values[2] - values[0]); if( canvas ) // Canvas has y axis upside down scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height(); getOrCreateStateSet()->setAttributeAndModes(scissor); } //---------------------------------------------------------------------------- void Element::setBoundingBox(const osg::BoundingBox& bb) { if( _bounding_box.empty() ) { SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true); _bounding_box.resize(4); _bounding_box[0] = bb_node->getChild("min-x", 0, true); _bounding_box[1] = bb_node->getChild("min-y", 0, true); _bounding_box[2] = bb_node->getChild("max-x", 0, true); _bounding_box[3] = bb_node->getChild("max-y", 0, true); } _bounding_box[0]->setFloatValue(bb._min.x()); _bounding_box[1]->setFloatValue(bb._min.y()); _bounding_box[2]->setFloatValue(bb._max.x()); _bounding_box[3]->setFloatValue(bb._max.y()); } //---------------------------------------------------------------------------- osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const { if( !_drawable ) return osg::BoundingBox(); osg::BoundingBox transformed; const osg::BoundingBox& bb = _drawable->getBound(); for(int i = 0; i < 4; ++i) transformed.expandBy( m * bb.corner(i) ); return transformed; } //---------------------------------------------------------------------------- Element::Element( const CanvasWeakPtr& canvas, const SGPropertyNode_ptr& node, const Style& parent_style, Element* parent ): PropertyBasedElement(node), _canvas( canvas ), _parent( parent ), _transform_dirty( false ), _transform( new osg::MatrixTransform ), _style( parent_style ), _drawable( 0 ) { SG_LOG ( SG_GL, SG_DEBUG, "New canvas element " << node->getPath() ); addStyle("clip", &Element::setClip, this); } //---------------------------------------------------------------------------- void Element::setDrawable( osg::Drawable* drawable ) { _drawable = drawable; assert( _drawable ); osg::ref_ptr<osg::Geode> geode = new osg::Geode; geode->addDrawable(_drawable); _transform->addChild(geode); } //---------------------------------------------------------------------------- osg::StateSet* Element::getOrCreateStateSet() { return _drawable ? _drawable->getOrCreateStateSet() : _transform->getOrCreateStateSet(); } //---------------------------------------------------------------------------- void Element::setupStyle() { BOOST_FOREACH( Style::value_type style, _style ) setStyle(style.second); } } // namespace canvas } // namespace simgear <|endoftext|>
<commit_before>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Read language depeneded messagefile */ #include "mysql_priv.h" #include "mysys_err.h" static void read_texts(const char *file_name,const char ***point, uint error_messages); static void init_myfunc_errs(void); /* Read messages from errorfile */ void init_errmessage(void) { DBUG_ENTER("init_errmessage"); read_texts(ERRMSG_FILE,&my_errmsg[ERRMAPP],ER_ERROR_MESSAGES); errmesg=my_errmsg[ERRMAPP]; /* Init global variabel */ init_myfunc_errs(); /* Init myfunc messages */ DBUG_VOID_RETURN; } /* Read text from packed textfile in language-directory */ /* If we can't read messagefile then it's panic- we can't continue */ static void read_texts(const char *file_name,const char ***point, uint error_messages) { register uint i; uint count,funktpos,length,textcount; File file; char name[FN_REFLEN]; const char *buff; uchar head[32],*pos; CHARSET_INFO *cset; DBUG_ENTER("read_texts"); *point=0; // If something goes wrong LINT_INIT(buff); funktpos=0; if ((file=my_open(fn_format(name,file_name,language,"",4), O_RDONLY | O_SHARE | O_BINARY, MYF(0))) < 0) goto err; /* purecov: inspected */ funktpos=1; if (my_read(file,(byte*) head,32,MYF(MY_NABP))) goto err; if (head[0] != (uchar) 254 || head[1] != (uchar) 254 || head[2] != 2 || head[3] != 1) goto err; /* purecov: inspected */ textcount=head[4]; if (!head[30]) { sql_print_error("No character set information in '%s'. \ You probably haven't reinstalled the latest file version.",name); goto err1; } if (!(cset= get_charset(head[30],MYF(MY_WME)))) { sql_print_error("Character set #%d is not supported for messagefile '%s'", (int)head[30],name); goto err1; } length=uint2korr(head+6); count=uint2korr(head+8); if (count < error_messages) { sql_print_error("\ Error message file '%s' had only %d error messages,\n\ but it should contain at least %d error messages.\n\ Check that the above file is the right version for this program!", name,count,error_messages); VOID(my_close(file,MYF(MY_WME))); unireg_abort(1); } x_free((gptr) *point); /* Free old language */ if (!(*point= (const char**) my_malloc((uint) (length+count*sizeof(char*)),MYF(0)))) { funktpos=2; /* purecov: inspected */ goto err; /* purecov: inspected */ } buff= (char*) (*point + count); if (my_read(file,(byte*) buff,(uint) count*2,MYF(MY_NABP))) goto err; for (i=0, pos= (uchar*) buff ; i< count ; i++) { (*point)[i]=buff+uint2korr(pos); pos+=2; } if (my_read(file,(byte*) buff,(uint) length,MYF(MY_NABP))) goto err; for (i=1 ; i < textcount ; i++) { point[i]= *point +uint2korr(head+10+i+i); } VOID(my_close(file,MYF(0))); DBUG_VOID_RETURN; err: switch (funktpos) { case 2: buff="Not enough memory for messagefile '%s'"; break; case 1: buff="Can't read from messagefile '%s'"; break; default: buff="Can't find messagefile '%s'"; break; } sql_print_error(buff,name); err1: if (file != FERR) VOID(my_close(file,MYF(MY_WME))); unireg_abort(1); } /* read_texts */ /* Initiates error-messages used by my_func-library */ static void init_myfunc_errs() { init_glob_errs(); /* Initiate english errors */ if (!(specialflag & SPECIAL_ENGLISH)) { globerrs[EE_FILENOTFOUND % ERRMOD] = ER(ER_FILE_NOT_FOUND); globerrs[EE_CANTCREATEFILE % ERRMOD]= ER(ER_CANT_CREATE_FILE); globerrs[EE_READ % ERRMOD] = ER(ER_ERROR_ON_READ); globerrs[EE_WRITE % ERRMOD] = ER(ER_ERROR_ON_WRITE); globerrs[EE_BADCLOSE % ERRMOD] = ER(ER_ERROR_ON_CLOSE); globerrs[EE_OUTOFMEMORY % ERRMOD] = ER(ER_OUTOFMEMORY); globerrs[EE_DELETE % ERRMOD] = ER(ER_CANT_DELETE_FILE); globerrs[EE_LINK % ERRMOD] = ER(ER_ERROR_ON_RENAME); globerrs[EE_EOFERR % ERRMOD] = ER(ER_UNEXPECTED_EOF); globerrs[EE_CANTLOCK % ERRMOD] = ER(ER_CANT_LOCK); globerrs[EE_DIR % ERRMOD] = ER(ER_CANT_READ_DIR); globerrs[EE_STAT % ERRMOD] = ER(ER_CANT_GET_STAT); globerrs[EE_GETWD % ERRMOD] = ER(ER_CANT_GET_WD); globerrs[EE_SETWD % ERRMOD] = ER(ER_CANT_SET_WD); globerrs[EE_DISK_FULL % ERRMOD] = ER(ER_DISK_FULL); } } <commit_msg>derror.cc: Better English message<commit_after>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Read language depeneded messagefile */ #include "mysql_priv.h" #include "mysys_err.h" static void read_texts(const char *file_name,const char ***point, uint error_messages); static void init_myfunc_errs(void); /* Read messages from errorfile */ void init_errmessage(void) { DBUG_ENTER("init_errmessage"); read_texts(ERRMSG_FILE,&my_errmsg[ERRMAPP],ER_ERROR_MESSAGES); errmesg=my_errmsg[ERRMAPP]; /* Init global variabel */ init_myfunc_errs(); /* Init myfunc messages */ DBUG_VOID_RETURN; } /* Read text from packed textfile in language-directory */ /* If we can't read messagefile then it's panic- we can't continue */ static void read_texts(const char *file_name,const char ***point, uint error_messages) { register uint i; uint count,funktpos,length,textcount; File file; char name[FN_REFLEN]; const char *buff; uchar head[32],*pos; CHARSET_INFO *cset; DBUG_ENTER("read_texts"); *point=0; // If something goes wrong LINT_INIT(buff); funktpos=0; if ((file=my_open(fn_format(name,file_name,language,"",4), O_RDONLY | O_SHARE | O_BINARY, MYF(0))) < 0) goto err; /* purecov: inspected */ funktpos=1; if (my_read(file,(byte*) head,32,MYF(MY_NABP))) goto err; if (head[0] != (uchar) 254 || head[1] != (uchar) 254 || head[2] != 2 || head[3] != 1) goto err; /* purecov: inspected */ textcount=head[4]; if (!head[30]) { sql_print_error("Character set information in not found in '%s'. \ Please install the latest version of this file.",name); goto err1; } if (!(cset= get_charset(head[30],MYF(MY_WME)))) { sql_print_error("Character set #%d is not supported for messagefile '%s'", (int)head[30],name); goto err1; } length=uint2korr(head+6); count=uint2korr(head+8); if (count < error_messages) { sql_print_error("\ Error message file '%s' had only %d error messages,\n\ but it should contain at least %d error messages.\n\ Check that the above file is the right version for this program!", name,count,error_messages); VOID(my_close(file,MYF(MY_WME))); unireg_abort(1); } x_free((gptr) *point); /* Free old language */ if (!(*point= (const char**) my_malloc((uint) (length+count*sizeof(char*)),MYF(0)))) { funktpos=2; /* purecov: inspected */ goto err; /* purecov: inspected */ } buff= (char*) (*point + count); if (my_read(file,(byte*) buff,(uint) count*2,MYF(MY_NABP))) goto err; for (i=0, pos= (uchar*) buff ; i< count ; i++) { (*point)[i]=buff+uint2korr(pos); pos+=2; } if (my_read(file,(byte*) buff,(uint) length,MYF(MY_NABP))) goto err; for (i=1 ; i < textcount ; i++) { point[i]= *point +uint2korr(head+10+i+i); } VOID(my_close(file,MYF(0))); DBUG_VOID_RETURN; err: switch (funktpos) { case 2: buff="Not enough memory for messagefile '%s'"; break; case 1: buff="Can't read from messagefile '%s'"; break; default: buff="Can't find messagefile '%s'"; break; } sql_print_error(buff,name); err1: if (file != FERR) VOID(my_close(file,MYF(MY_WME))); unireg_abort(1); } /* read_texts */ /* Initiates error-messages used by my_func-library */ static void init_myfunc_errs() { init_glob_errs(); /* Initiate english errors */ if (!(specialflag & SPECIAL_ENGLISH)) { globerrs[EE_FILENOTFOUND % ERRMOD] = ER(ER_FILE_NOT_FOUND); globerrs[EE_CANTCREATEFILE % ERRMOD]= ER(ER_CANT_CREATE_FILE); globerrs[EE_READ % ERRMOD] = ER(ER_ERROR_ON_READ); globerrs[EE_WRITE % ERRMOD] = ER(ER_ERROR_ON_WRITE); globerrs[EE_BADCLOSE % ERRMOD] = ER(ER_ERROR_ON_CLOSE); globerrs[EE_OUTOFMEMORY % ERRMOD] = ER(ER_OUTOFMEMORY); globerrs[EE_DELETE % ERRMOD] = ER(ER_CANT_DELETE_FILE); globerrs[EE_LINK % ERRMOD] = ER(ER_ERROR_ON_RENAME); globerrs[EE_EOFERR % ERRMOD] = ER(ER_UNEXPECTED_EOF); globerrs[EE_CANTLOCK % ERRMOD] = ER(ER_CANT_LOCK); globerrs[EE_DIR % ERRMOD] = ER(ER_CANT_READ_DIR); globerrs[EE_STAT % ERRMOD] = ER(ER_CANT_GET_STAT); globerrs[EE_GETWD % ERRMOD] = ER(ER_CANT_GET_WD); globerrs[EE_SETWD % ERRMOD] = ER(ER_CANT_SET_WD); globerrs[EE_DISK_FULL % ERRMOD] = ER(ER_DISK_FULL); } } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/operators/box_coder_op.h" namespace paddle { namespace operators { class BoxCoderOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; protected: void InferShape(framework::InferShapeContext *ctx) const override { PADDLE_ENFORCE(ctx->HasInput("PriorBox"), "Input(PriorBox) of BoxCoderOp should not be null."); PADDLE_ENFORCE(ctx->HasInput("PriorBoxVar"), "Input(PriorBoxVar) of BoxCoderOp should not be null."); PADDLE_ENFORCE(ctx->HasInput("PriorBox"), "Input(TargetBox) of BoxCoderOp should not be null."); auto prior_box_dims = ctx->GetInputDim("PriorBox"); auto prior_box_var_dims = ctx->GetInputDim("PriorBoxVar"); auto target_box_dims = ctx->GetInputDim("TargetBox"); PADDLE_ENFORCE_EQ(prior_box_dims.size(), 2UL, "The shape of PriorBox is [N, 4]"); PADDLE_ENFORCE_EQ(prior_box_dims[1], 4UL, "The shape of PriorBox is [N, 4]"); PADDLE_ENFORCE_EQ(prior_box_var_dims.size(), 2UL, "The shape of PriorBoxVar is [N, 4]"); PADDLE_ENFORCE_EQ(prior_box_var_dims[1], 4UL, "The shape of PriorBoxVar is [N, 4]"); PADDLE_ENFORCE_EQ(target_box_dims.size(), 2UL, "The shape of TargetBox is [M, 4]"); PADDLE_ENFORCE_EQ(target_box_dims[1], 4UL, "The shape of TargetBox is [M, 4]"); GetBoxCodeType(ctx->Attrs().Get<std::string>("code_type")); ctx->SetOutputDim("OutputBox", framework::make_ddim({target_box_dims[0], target_box_dims[1]})); } }; class BoxCoderOpMaker : public framework::OpProtoAndCheckerMaker { public: BoxCoderOpMaker(OpProto *proto, OpAttrChecker *op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput( "PriorBox", "(Tensor, default Tensor<float>) " "Box list PriorBox is a 2-D Tensor with shape [M, 4] holds N boxes, " "each box is represented as [xmin, ymin, xmax, ymax], " "[xmin, ymin] is the left top coordinate of the anchor box, " "if the input is image feature map, they are close to the origin " "of the coordinate system. [xmax, ymax] is the right bottom " "coordinate of the anchor box."); AddInput("PriorBoxVar", "(Tensor, default Tensor<float>) " "PriorBoxVar is a 2-D Tensor with shape [M, 4] holds N group " "of variance."); AddInput( "TargetBox", "(LoDTensor or Tensor) this input is a 2-D LoDTensor with shape " "[N, 4], each box is represented as [xmin, ymin, xmax, ymax], " "[xmin, ymin] is the left top coordinate of the box if the input " "is image feature map, they are close to the origin of the coordinate " "system. [xmax, ymax] is the right bottom coordinate of the box. " "This tensor can contain LoD information to represent a batch " "of inputs. One instance of this batch can contain different " "numbers of entities."); AddAttr<std::string>("code_type", "(string, default encode_center_size) " "the code type used with the target box") .SetDefault("encode_center_size") .InEnum({"encode_center_size", "decode_center_size"}); AddOutput( "OutputBox", "(Tensor, default Tensor<float>)" "(Tensor) The output of box_coder_op, a tensor with shape [N, M, 4] " "representing the result of N target boxes encoded/decoded with " "M Prior boxes and variances."); AddComment(R"DOC( Bounding Box Coder Operator. Encode/Decode the priorbox information with the target bounding box. )DOC"); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_WITHOUT_GRADIENT(box_coder, ops::BoxCoderOp, ops::BoxCoderOpMaker); REGISTER_OP_CPU_KERNEL(box_coder, ops::BoxCoderKernel<float>, ops::BoxCoderKernel<double>); <commit_msg>Update box_coder_op.cc<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/operators/box_coder_op.h" namespace paddle { namespace operators { class BoxCoderOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; protected: void InferShape(framework::InferShapeContext *ctx) const override { PADDLE_ENFORCE(ctx->HasInput("PriorBox"), "Input(PriorBox) of BoxCoderOp should not be null."); PADDLE_ENFORCE(ctx->HasInput("PriorBoxVar"), "Input(PriorBoxVar) of BoxCoderOp should not be null."); PADDLE_ENFORCE(ctx->HasInput("PriorBox"), "Input(TargetBox) of BoxCoderOp should not be null."); auto prior_box_dims = ctx->GetInputDim("PriorBox"); auto prior_box_var_dims = ctx->GetInputDim("PriorBoxVar"); auto target_box_dims = ctx->GetInputDim("TargetBox"); PADDLE_ENFORCE_EQ(prior_box_dims.size(), 2UL, "The rank of Input of PriorBox must be 2"); PADDLE_ENFORCE_EQ(prior_box_dims[1], 4UL, "The shape of PriorBox is [N, 4]"); PADDLE_ENFORCE_EQ(prior_box_var_dims.size(), 2UL, "The rank of Input of PriorBoxVar must be 2"); PADDLE_ENFORCE_EQ(prior_box_var_dims[1], 4UL, "The shape of PriorBoxVar is [N, 4]"); PADDLE_ENFORCE_EQ(target_box_dims.size(), 2UL, "The rank of Input of TargetBox must be 2"); PADDLE_ENFORCE_EQ(target_box_dims[1], 4UL, "The shape of TargetBox is [M, 4]"); GetBoxCodeType(ctx->Attrs().Get<std::string>("code_type")); ctx->SetOutputDim("OutputBox", framework::make_ddim({target_box_dims[0], target_box_dims[1]})); } }; class BoxCoderOpMaker : public framework::OpProtoAndCheckerMaker { public: BoxCoderOpMaker(OpProto *proto, OpAttrChecker *op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput( "PriorBox", "(Tensor, default Tensor<float>) " "Box list PriorBox is a 2-D Tensor with shape [M, 4] holds N boxes, " "each box is represented as [xmin, ymin, xmax, ymax], " "[xmin, ymin] is the left top coordinate of the anchor box, " "if the input is image feature map, they are close to the origin " "of the coordinate system. [xmax, ymax] is the right bottom " "coordinate of the anchor box."); AddInput("PriorBoxVar", "(Tensor, default Tensor<float>) " "PriorBoxVar is a 2-D Tensor with shape [M, 4] holds N group " "of variance."); AddInput( "TargetBox", "(LoDTensor or Tensor) this input is a 2-D LoDTensor with shape " "[N, 4], each box is represented as [xmin, ymin, xmax, ymax], " "[xmin, ymin] is the left top coordinate of the box if the input " "is image feature map, they are close to the origin of the coordinate " "system. [xmax, ymax] is the right bottom coordinate of the box. " "This tensor can contain LoD information to represent a batch " "of inputs. One instance of this batch can contain different " "numbers of entities."); AddAttr<std::string>("code_type", "(string, default encode_center_size) " "the code type used with the target box") .SetDefault("encode_center_size") .InEnum({"encode_center_size", "decode_center_size"}); AddOutput( "OutputBox", "(Tensor, default Tensor<float>)" "(Tensor) The output of box_coder_op, a tensor with shape [N, M, 4] " "representing the result of N target boxes encoded/decoded with " "M Prior boxes and variances."); AddComment(R"DOC( Bounding Box Coder Operator. Encode/Decode the priorbox information with the target bounding box. )DOC"); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_WITHOUT_GRADIENT(box_coder, ops::BoxCoderOp, ops::BoxCoderOpMaker); REGISTER_OP_CPU_KERNEL(box_coder, ops::BoxCoderKernel<float>, ops::BoxCoderKernel<double>); <|endoftext|>
<commit_before>//===- llvm/unittest/ADT/ValueMapTest.cpp - ValueMap unit tests -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/ValueMap.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/Config/llvm-config.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "gtest/gtest.h" using namespace llvm; namespace { // Test fixture template<typename T> class ValueMapTest : public testing::Test { protected: Constant *ConstantV; OwningPtr<BitCastInst> BitcastV; OwningPtr<BinaryOperator> AddV; ValueMapTest() : ConstantV(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0)), BitcastV(new BitCastInst(ConstantV, Type::getInt32Ty(getGlobalContext()))), AddV(BinaryOperator::CreateAdd(ConstantV, ConstantV)) { } }; // Run everything on Value*, a subtype to make sure that casting works as // expected, and a const subtype to make sure we cast const correctly. typedef ::testing::Types<Value, Instruction, const Instruction> KeyTypes; TYPED_TEST_CASE(ValueMapTest, KeyTypes); TYPED_TEST(ValueMapTest, Null) { ValueMap<TypeParam*, int> VM1; VM1[NULL] = 7; EXPECT_EQ(7, VM1.lookup(NULL)); } TYPED_TEST(ValueMapTest, FollowsValue) { ValueMap<TypeParam*, int> VM; VM[this->BitcastV.get()] = 7; EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.count(this->AddV.get())); this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(7, VM.lookup(this->AddV.get())); EXPECT_EQ(0, VM.count(this->BitcastV.get())); this->AddV.reset(); EXPECT_EQ(0, VM.count(this->AddV.get())); EXPECT_EQ(0, VM.count(this->BitcastV.get())); EXPECT_EQ(0U, VM.size()); } TYPED_TEST(ValueMapTest, OperationsWork) { ValueMap<TypeParam*, int> VM; ValueMap<TypeParam*, int> VM2(16); (void)VM2; typename ValueMapConfig<TypeParam*>::ExtraData Data; ValueMap<TypeParam*, int> VM3(Data, 16); (void)VM3; EXPECT_TRUE(VM.empty()); VM[this->BitcastV.get()] = 7; // Find: typename ValueMap<TypeParam*, int>::iterator I = VM.find(this->BitcastV.get()); ASSERT_TRUE(I != VM.end()); EXPECT_EQ(this->BitcastV.get(), I->first); EXPECT_EQ(7, I->second); EXPECT_TRUE(VM.find(this->AddV.get()) == VM.end()); // Const find: const ValueMap<TypeParam*, int> &CVM = VM; typename ValueMap<TypeParam*, int>::const_iterator CI = CVM.find(this->BitcastV.get()); ASSERT_TRUE(CI != CVM.end()); EXPECT_EQ(this->BitcastV.get(), CI->first); EXPECT_EQ(7, CI->second); EXPECT_TRUE(CVM.find(this->AddV.get()) == CVM.end()); // Insert: std::pair<typename ValueMap<TypeParam*, int>::iterator, bool> InsertResult1 = VM.insert(std::make_pair(this->AddV.get(), 3)); EXPECT_EQ(this->AddV.get(), InsertResult1.first->first); EXPECT_EQ(3, InsertResult1.first->second); EXPECT_TRUE(InsertResult1.second); EXPECT_EQ(true, VM.count(this->AddV.get())); std::pair<typename ValueMap<TypeParam*, int>::iterator, bool> InsertResult2 = VM.insert(std::make_pair(this->AddV.get(), 5)); EXPECT_EQ(this->AddV.get(), InsertResult2.first->first); EXPECT_EQ(3, InsertResult2.first->second); EXPECT_FALSE(InsertResult2.second); // Erase: VM.erase(InsertResult2.first); EXPECT_EQ(0U, VM.count(this->AddV.get())); EXPECT_EQ(1U, VM.count(this->BitcastV.get())); VM.erase(this->BitcastV.get()); EXPECT_EQ(0U, VM.count(this->BitcastV.get())); EXPECT_EQ(0U, VM.size()); // Range insert: SmallVector<std::pair<Instruction*, int>, 2> Elems; Elems.push_back(std::make_pair(this->AddV.get(), 1)); Elems.push_back(std::make_pair(this->BitcastV.get(), 2)); VM.insert(Elems.begin(), Elems.end()); EXPECT_EQ(1, VM.lookup(this->AddV.get())); EXPECT_EQ(2, VM.lookup(this->BitcastV.get())); } template<typename ExpectedType, typename VarType> void CompileAssertHasType(VarType) { typedef char assert[is_same<ExpectedType, VarType>::value ? 1 : -1]; } TYPED_TEST(ValueMapTest, Iteration) { ValueMap<TypeParam*, int> VM; VM[this->BitcastV.get()] = 2; VM[this->AddV.get()] = 3; size_t size = 0; for (typename ValueMap<TypeParam*, int>::iterator I = VM.begin(), E = VM.end(); I != E; ++I) { ++size; std::pair<TypeParam*, int> value = *I; (void)value; CompileAssertHasType<TypeParam*>(I->first); if (I->second == 2) { EXPECT_EQ(this->BitcastV.get(), I->first); I->second = 5; } else if (I->second == 3) { EXPECT_EQ(this->AddV.get(), I->first); I->second = 6; } else { ADD_FAILURE() << "Iterated through an extra value."; } } EXPECT_EQ(2U, size); EXPECT_EQ(5, VM[this->BitcastV.get()]); EXPECT_EQ(6, VM[this->AddV.get()]); size = 0; // Cast to const ValueMap to avoid a bug in DenseMap's iterators. const ValueMap<TypeParam*, int>& CVM = VM; for (typename ValueMap<TypeParam*, int>::const_iterator I = CVM.begin(), E = CVM.end(); I != E; ++I) { ++size; std::pair<TypeParam*, int> value = *I; (void)value; CompileAssertHasType<TypeParam*>(I->first); if (I->second == 5) { EXPECT_EQ(this->BitcastV.get(), I->first); } else if (I->second == 6) { EXPECT_EQ(this->AddV.get(), I->first); } else { ADD_FAILURE() << "Iterated through an extra value."; } } EXPECT_EQ(2U, size); } TYPED_TEST(ValueMapTest, DefaultCollisionBehavior) { // By default, we overwrite the old value with the replaced value. ValueMap<TypeParam*, int> VM; VM[this->BitcastV.get()] = 7; VM[this->AddV.get()] = 9; this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(0, VM.count(this->BitcastV.get())); EXPECT_EQ(9, VM.lookup(this->AddV.get())); } TYPED_TEST(ValueMapTest, ConfiguredCollisionBehavior) { // TODO: Implement this when someone needs it. } template<typename KeyT> struct LockMutex : ValueMapConfig<KeyT> { struct ExtraData { sys::Mutex *M; bool *CalledRAUW; bool *CalledDeleted; }; static void onRAUW(const ExtraData &Data, KeyT Old, KeyT New) { *Data.CalledRAUW = true; EXPECT_FALSE(Data.M->tryacquire()) << "Mutex should already be locked."; } static void onDelete(const ExtraData &Data, KeyT Old) { *Data.CalledDeleted = true; EXPECT_FALSE(Data.M->tryacquire()) << "Mutex should already be locked."; } static sys::Mutex *getMutex(const ExtraData &Data) { return Data.M; } }; #if LLVM_ENABLE_THREADS TYPED_TEST(ValueMapTest, LocksMutex) { sys::Mutex M(false); // Not recursive. bool CalledRAUW = false, CalledDeleted = false; typename LockMutex<TypeParam*>::ExtraData Data = {&M, &CalledRAUW, &CalledDeleted}; ValueMap<TypeParam*, int, LockMutex<TypeParam*> > VM(Data); VM[this->BitcastV.get()] = 7; this->BitcastV->replaceAllUsesWith(this->AddV.get()); this->AddV.reset(); EXPECT_TRUE(CalledRAUW); EXPECT_TRUE(CalledDeleted); } #endif template<typename KeyT> struct NoFollow : ValueMapConfig<KeyT> { enum { FollowRAUW = false }; }; TYPED_TEST(ValueMapTest, NoFollowRAUW) { ValueMap<TypeParam*, int, NoFollow<TypeParam*> > VM; VM[this->BitcastV.get()] = 7; EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.count(this->AddV.get())); this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.lookup(this->AddV.get())); this->AddV.reset(); EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.lookup(this->AddV.get())); this->BitcastV.reset(); EXPECT_EQ(0, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.lookup(this->AddV.get())); EXPECT_EQ(0U, VM.size()); } template<typename KeyT> struct CountOps : ValueMapConfig<KeyT> { struct ExtraData { int *Deletions; int *RAUWs; }; static void onRAUW(const ExtraData &Data, KeyT Old, KeyT New) { ++*Data.RAUWs; } static void onDelete(const ExtraData &Data, KeyT Old) { ++*Data.Deletions; } }; TYPED_TEST(ValueMapTest, CallsConfig) { int Deletions = 0, RAUWs = 0; typename CountOps<TypeParam*>::ExtraData Data = {&Deletions, &RAUWs}; ValueMap<TypeParam*, int, CountOps<TypeParam*> > VM(Data); VM[this->BitcastV.get()] = 7; this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(0, Deletions); EXPECT_EQ(1, RAUWs); this->AddV.reset(); EXPECT_EQ(1, Deletions); EXPECT_EQ(1, RAUWs); this->BitcastV.reset(); EXPECT_EQ(1, Deletions); EXPECT_EQ(1, RAUWs); } template<typename KeyT> struct ModifyingConfig : ValueMapConfig<KeyT> { // We'll put a pointer here back to the ValueMap this key is in, so // that we can modify it (and clobber *this) before the ValueMap // tries to do the same modification. In previous versions of // ValueMap, that exploded. typedef ValueMap<KeyT, int, ModifyingConfig<KeyT> > **ExtraData; static void onRAUW(ExtraData Map, KeyT Old, KeyT New) { (*Map)->erase(Old); } static void onDelete(ExtraData Map, KeyT Old) { (*Map)->erase(Old); } }; TYPED_TEST(ValueMapTest, SurvivesModificationByConfig) { ValueMap<TypeParam*, int, ModifyingConfig<TypeParam*> > *MapAddress; ValueMap<TypeParam*, int, ModifyingConfig<TypeParam*> > VM(&MapAddress); MapAddress = &VM; // Now the ModifyingConfig can modify the Map inside a callback. VM[this->BitcastV.get()] = 7; this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_FALSE(VM.count(this->BitcastV.get())); EXPECT_FALSE(VM.count(this->AddV.get())); VM[this->AddV.get()] = 7; this->AddV.reset(); EXPECT_FALSE(VM.count(this->AddV.get())); } } <commit_msg>Silence g++ 4.9 build issue in unit tests<commit_after>//===- llvm/unittest/ADT/ValueMapTest.cpp - ValueMap unit tests -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/ValueMap.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/Config/llvm-config.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "gtest/gtest.h" using namespace llvm; namespace { // Test fixture template<typename T> class ValueMapTest : public testing::Test { protected: Constant *ConstantV; OwningPtr<BitCastInst> BitcastV; OwningPtr<BinaryOperator> AddV; ValueMapTest() : ConstantV(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0)), BitcastV(new BitCastInst(ConstantV, Type::getInt32Ty(getGlobalContext()))), AddV(BinaryOperator::CreateAdd(ConstantV, ConstantV)) { } }; // Run everything on Value*, a subtype to make sure that casting works as // expected, and a const subtype to make sure we cast const correctly. typedef ::testing::Types<Value, Instruction, const Instruction> KeyTypes; TYPED_TEST_CASE(ValueMapTest, KeyTypes); TYPED_TEST(ValueMapTest, Null) { ValueMap<TypeParam*, int> VM1; VM1[NULL] = 7; EXPECT_EQ(7, VM1.lookup(NULL)); } TYPED_TEST(ValueMapTest, FollowsValue) { ValueMap<TypeParam*, int> VM; VM[this->BitcastV.get()] = 7; EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.count(this->AddV.get())); this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(7, VM.lookup(this->AddV.get())); EXPECT_EQ(0, VM.count(this->BitcastV.get())); this->AddV.reset(); EXPECT_EQ(0, VM.count(this->AddV.get())); EXPECT_EQ(0, VM.count(this->BitcastV.get())); EXPECT_EQ(0U, VM.size()); } TYPED_TEST(ValueMapTest, OperationsWork) { ValueMap<TypeParam*, int> VM; ValueMap<TypeParam*, int> VM2(16); (void)VM2; typename ValueMapConfig<TypeParam*>::ExtraData Data; ValueMap<TypeParam*, int> VM3(Data, 16); (void)VM3; EXPECT_TRUE(VM.empty()); VM[this->BitcastV.get()] = 7; // Find: typename ValueMap<TypeParam*, int>::iterator I = VM.find(this->BitcastV.get()); ASSERT_TRUE(I != VM.end()); EXPECT_EQ(this->BitcastV.get(), I->first); EXPECT_EQ(7, I->second); EXPECT_TRUE(VM.find(this->AddV.get()) == VM.end()); // Const find: const ValueMap<TypeParam*, int> &CVM = VM; typename ValueMap<TypeParam*, int>::const_iterator CI = CVM.find(this->BitcastV.get()); ASSERT_TRUE(CI != CVM.end()); EXPECT_EQ(this->BitcastV.get(), CI->first); EXPECT_EQ(7, CI->second); EXPECT_TRUE(CVM.find(this->AddV.get()) == CVM.end()); // Insert: std::pair<typename ValueMap<TypeParam*, int>::iterator, bool> InsertResult1 = VM.insert(std::make_pair(this->AddV.get(), 3)); EXPECT_EQ(this->AddV.get(), InsertResult1.first->first); EXPECT_EQ(3, InsertResult1.first->second); EXPECT_TRUE(InsertResult1.second); EXPECT_EQ(true, VM.count(this->AddV.get())); std::pair<typename ValueMap<TypeParam*, int>::iterator, bool> InsertResult2 = VM.insert(std::make_pair(this->AddV.get(), 5)); EXPECT_EQ(this->AddV.get(), InsertResult2.first->first); EXPECT_EQ(3, InsertResult2.first->second); EXPECT_FALSE(InsertResult2.second); // Erase: VM.erase(InsertResult2.first); EXPECT_EQ(0U, VM.count(this->AddV.get())); EXPECT_EQ(1U, VM.count(this->BitcastV.get())); VM.erase(this->BitcastV.get()); EXPECT_EQ(0U, VM.count(this->BitcastV.get())); EXPECT_EQ(0U, VM.size()); // Range insert: SmallVector<std::pair<Instruction*, int>, 2> Elems; Elems.push_back(std::make_pair(this->AddV.get(), 1)); Elems.push_back(std::make_pair(this->BitcastV.get(), 2)); VM.insert(Elems.begin(), Elems.end()); EXPECT_EQ(1, VM.lookup(this->AddV.get())); EXPECT_EQ(2, VM.lookup(this->BitcastV.get())); } template<typename ExpectedType, typename VarType> void CompileAssertHasType(VarType) { LLVM_ATTRIBUTE_UNUSED typedef char assert[is_same<ExpectedType, VarType>::value ? 1 : -1]; } TYPED_TEST(ValueMapTest, Iteration) { ValueMap<TypeParam*, int> VM; VM[this->BitcastV.get()] = 2; VM[this->AddV.get()] = 3; size_t size = 0; for (typename ValueMap<TypeParam*, int>::iterator I = VM.begin(), E = VM.end(); I != E; ++I) { ++size; std::pair<TypeParam*, int> value = *I; (void)value; CompileAssertHasType<TypeParam*>(I->first); if (I->second == 2) { EXPECT_EQ(this->BitcastV.get(), I->first); I->second = 5; } else if (I->second == 3) { EXPECT_EQ(this->AddV.get(), I->first); I->second = 6; } else { ADD_FAILURE() << "Iterated through an extra value."; } } EXPECT_EQ(2U, size); EXPECT_EQ(5, VM[this->BitcastV.get()]); EXPECT_EQ(6, VM[this->AddV.get()]); size = 0; // Cast to const ValueMap to avoid a bug in DenseMap's iterators. const ValueMap<TypeParam*, int>& CVM = VM; for (typename ValueMap<TypeParam*, int>::const_iterator I = CVM.begin(), E = CVM.end(); I != E; ++I) { ++size; std::pair<TypeParam*, int> value = *I; (void)value; CompileAssertHasType<TypeParam*>(I->first); if (I->second == 5) { EXPECT_EQ(this->BitcastV.get(), I->first); } else if (I->second == 6) { EXPECT_EQ(this->AddV.get(), I->first); } else { ADD_FAILURE() << "Iterated through an extra value."; } } EXPECT_EQ(2U, size); } TYPED_TEST(ValueMapTest, DefaultCollisionBehavior) { // By default, we overwrite the old value with the replaced value. ValueMap<TypeParam*, int> VM; VM[this->BitcastV.get()] = 7; VM[this->AddV.get()] = 9; this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(0, VM.count(this->BitcastV.get())); EXPECT_EQ(9, VM.lookup(this->AddV.get())); } TYPED_TEST(ValueMapTest, ConfiguredCollisionBehavior) { // TODO: Implement this when someone needs it. } template<typename KeyT> struct LockMutex : ValueMapConfig<KeyT> { struct ExtraData { sys::Mutex *M; bool *CalledRAUW; bool *CalledDeleted; }; static void onRAUW(const ExtraData &Data, KeyT Old, KeyT New) { *Data.CalledRAUW = true; EXPECT_FALSE(Data.M->tryacquire()) << "Mutex should already be locked."; } static void onDelete(const ExtraData &Data, KeyT Old) { *Data.CalledDeleted = true; EXPECT_FALSE(Data.M->tryacquire()) << "Mutex should already be locked."; } static sys::Mutex *getMutex(const ExtraData &Data) { return Data.M; } }; #if LLVM_ENABLE_THREADS TYPED_TEST(ValueMapTest, LocksMutex) { sys::Mutex M(false); // Not recursive. bool CalledRAUW = false, CalledDeleted = false; typename LockMutex<TypeParam*>::ExtraData Data = {&M, &CalledRAUW, &CalledDeleted}; ValueMap<TypeParam*, int, LockMutex<TypeParam*> > VM(Data); VM[this->BitcastV.get()] = 7; this->BitcastV->replaceAllUsesWith(this->AddV.get()); this->AddV.reset(); EXPECT_TRUE(CalledRAUW); EXPECT_TRUE(CalledDeleted); } #endif template<typename KeyT> struct NoFollow : ValueMapConfig<KeyT> { enum { FollowRAUW = false }; }; TYPED_TEST(ValueMapTest, NoFollowRAUW) { ValueMap<TypeParam*, int, NoFollow<TypeParam*> > VM; VM[this->BitcastV.get()] = 7; EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.count(this->AddV.get())); this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.lookup(this->AddV.get())); this->AddV.reset(); EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.lookup(this->AddV.get())); this->BitcastV.reset(); EXPECT_EQ(0, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.lookup(this->AddV.get())); EXPECT_EQ(0U, VM.size()); } template<typename KeyT> struct CountOps : ValueMapConfig<KeyT> { struct ExtraData { int *Deletions; int *RAUWs; }; static void onRAUW(const ExtraData &Data, KeyT Old, KeyT New) { ++*Data.RAUWs; } static void onDelete(const ExtraData &Data, KeyT Old) { ++*Data.Deletions; } }; TYPED_TEST(ValueMapTest, CallsConfig) { int Deletions = 0, RAUWs = 0; typename CountOps<TypeParam*>::ExtraData Data = {&Deletions, &RAUWs}; ValueMap<TypeParam*, int, CountOps<TypeParam*> > VM(Data); VM[this->BitcastV.get()] = 7; this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(0, Deletions); EXPECT_EQ(1, RAUWs); this->AddV.reset(); EXPECT_EQ(1, Deletions); EXPECT_EQ(1, RAUWs); this->BitcastV.reset(); EXPECT_EQ(1, Deletions); EXPECT_EQ(1, RAUWs); } template<typename KeyT> struct ModifyingConfig : ValueMapConfig<KeyT> { // We'll put a pointer here back to the ValueMap this key is in, so // that we can modify it (and clobber *this) before the ValueMap // tries to do the same modification. In previous versions of // ValueMap, that exploded. typedef ValueMap<KeyT, int, ModifyingConfig<KeyT> > **ExtraData; static void onRAUW(ExtraData Map, KeyT Old, KeyT New) { (*Map)->erase(Old); } static void onDelete(ExtraData Map, KeyT Old) { (*Map)->erase(Old); } }; TYPED_TEST(ValueMapTest, SurvivesModificationByConfig) { ValueMap<TypeParam*, int, ModifyingConfig<TypeParam*> > *MapAddress; ValueMap<TypeParam*, int, ModifyingConfig<TypeParam*> > VM(&MapAddress); MapAddress = &VM; // Now the ModifyingConfig can modify the Map inside a callback. VM[this->BitcastV.get()] = 7; this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_FALSE(VM.count(this->BitcastV.get())); EXPECT_FALSE(VM.count(this->AddV.get())); VM[this->AddV.get()] = 7; this->AddV.reset(); EXPECT_FALSE(VM.count(this->AddV.get())); } } <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2017 Robert Ou <rqou@robertou.com> * * 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 "kernel/yosys.h" #include "kernel/sigtools.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct ExtractReducePass : public Pass { enum GateType { And, Or, Xor }; ExtractReducePass() : Pass("extract_reduce", "converts gate chains into $reduce_* cells") { } virtual void help() { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" extract_reduce [selection]\n"); log("\n"); log("converts gate chains into $reduce_* cells\n"); log("\n"); log("This command finds chains of $_AND_, $_OR_, and $_XOR_ cells and replaces them\n"); log("with their corresponding $reduce_* cells. Because this command only operates on\n"); log("these cell types, it is recommended to map the design to only these cell types\n"); log("using the `abc -g` command. Note that, in some cases, it may be more effective\n"); log("to map the design to only $_AND_ cells, run extract_reduce, map the remaining\n"); log("parts of the design to AND/OR/XOR cells, and run extract_reduce a second time.\n"); log("\n"); } virtual void execute(std::vector<std::string> args, RTLIL::Design *design) { log_header(design, "Executing EXTRACT_REDUCE pass.\n"); log_push(); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { // if (args[argidx] == "-v") { // verbose = true; // continue; // } break; } extra_args(args, argidx, design); for (auto module : design->selected_modules()) { SigMap sigmap(module); // Index all of the nets in the module dict<SigBit, Cell*> sig_to_driver; dict<SigBit, pool<Cell*>> sig_to_sink; for (auto cell : module->selected_cells()) { for (auto &conn : cell->connections()) { if (cell->output(conn.first)) for (auto bit : sigmap(conn.second)) sig_to_driver[bit] = cell; if (cell->input(conn.first)) { for (auto bit : sigmap(conn.second)) { if (sig_to_sink.count(bit) == 0) sig_to_sink[bit] = pool<Cell*>(); sig_to_sink[bit].insert(cell); } } } } // Need to check if any wires connect to module ports pool<SigBit> port_sigs; for (auto wire : module->selected_wires()) if (wire->port_input || wire->port_output) for (auto bit : sigmap(wire)) port_sigs.insert(bit); // Actual logic starts here pool<Cell*> consumed_cells; for (auto cell : module->selected_cells()) { if (consumed_cells.count(cell)) continue; GateType gt; if (cell->type == "$_AND_") gt = GateType::And; else if (cell->type == "$_OR_") gt = GateType::Or; else if (cell->type == "$_XOR_") gt = GateType::Xor; else continue; log("Working on cell %s...\n", cell->name.c_str()); // Go all the way to the sink Cell* head_cell = cell; Cell* x = cell; while (true) { if (!((x->type == "$_AND_" && gt == GateType::And) || (x->type == "$_OR_" && gt == GateType::Or) || (x->type == "$_XOR_" && gt == GateType::Xor))) break; head_cell = x; auto y = sigmap(x->getPort("\\Y")); log_assert(y.size() == 1); // Should only continue if there is one fanout back into a cell (not to a port) if (sig_to_sink[y[0]].size() != 1) break; x = *sig_to_sink[y[0]].begin(); } log(" Head cell is %s\n", head_cell->name.c_str()); pool<Cell*> cur_supercell; std::deque<Cell*> bfs_queue = {head_cell}; while (bfs_queue.size()) { Cell* x = bfs_queue.front(); bfs_queue.pop_front(); cur_supercell.insert(x); auto a = sigmap(x->getPort("\\A")); log_assert(a.size() == 1); // Must have only one sink // XXX: Check that it is indeed this node? if (sig_to_sink[a[0]].size() + port_sigs.count(a[0]) == 1) { Cell* cell_a = sig_to_driver[a[0]]; if (((cell_a->type == "$_AND_" && gt == GateType::And) || (cell_a->type == "$_OR_" && gt == GateType::Or) || (cell_a->type == "$_XOR_" && gt == GateType::Xor))) { // The cell here is the correct type, and it's definitely driving only // this current cell. bfs_queue.push_back(cell_a); } } auto b = sigmap(x->getPort("\\B")); log_assert(b.size() == 1); // Must have only one sink // XXX: Check that it is indeed this node? if (sig_to_sink[b[0]].size() + port_sigs.count(b[0]) == 1) { Cell* cell_b = sig_to_driver[b[0]]; if (((cell_b->type == "$_AND_" && gt == GateType::And) || (cell_b->type == "$_OR_" && gt == GateType::Or) || (cell_b->type == "$_XOR_" && gt == GateType::Xor))) { // The cell here is the correct type, and it's definitely driving only // this current cell. bfs_queue.push_back(cell_b); } } } log(" Cells:\n"); for (auto x : cur_supercell) log(" %s\n", x->name.c_str()); if (cur_supercell.size() > 1) { // Worth it to create reduce cell log(" Creating $reduce_* cell!\n"); pool<SigBit> input_pool; pool<SigBit> input_pool_intermed; for (auto x : cur_supercell) { input_pool.insert(sigmap(x->getPort("\\A"))[0]); input_pool.insert(sigmap(x->getPort("\\B"))[0]); input_pool_intermed.insert(sigmap(x->getPort("\\Y"))[0]); } SigSpec input; for (auto b : input_pool) if (input_pool_intermed.count(b) == 0) input.append_bit(b); SigBit output = sigmap(head_cell->getPort("\\Y")[0]); auto new_reduce_cell = module->addCell(NEW_ID, gt == GateType::And ? "$reduce_and" : gt == GateType::Or ? "$reduce_or" : gt == GateType::Xor ? "$reduce_xor" : ""); new_reduce_cell->setParam("\\A_SIGNED", 0); new_reduce_cell->setParam("\\A_WIDTH", input.size()); new_reduce_cell->setParam("\\Y_WIDTH", 1); new_reduce_cell->setPort("\\A", input); new_reduce_cell->setPort("\\Y", output); for (auto x : cur_supercell) consumed_cells.insert(x); } } // Remove every cell that we've used up for (auto cell : consumed_cells) module->remove(cell); } log_pop(); } } ExtractReducePass; PRIVATE_NAMESPACE_END <commit_msg>extract_reduce: Fix segfault on "undriven" inputs<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2017 Robert Ou <rqou@robertou.com> * * 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 "kernel/yosys.h" #include "kernel/sigtools.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct ExtractReducePass : public Pass { enum GateType { And, Or, Xor }; ExtractReducePass() : Pass("extract_reduce", "converts gate chains into $reduce_* cells") { } virtual void help() { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" extract_reduce [selection]\n"); log("\n"); log("converts gate chains into $reduce_* cells\n"); log("\n"); log("This command finds chains of $_AND_, $_OR_, and $_XOR_ cells and replaces them\n"); log("with their corresponding $reduce_* cells. Because this command only operates on\n"); log("these cell types, it is recommended to map the design to only these cell types\n"); log("using the `abc -g` command. Note that, in some cases, it may be more effective\n"); log("to map the design to only $_AND_ cells, run extract_reduce, map the remaining\n"); log("parts of the design to AND/OR/XOR cells, and run extract_reduce a second time.\n"); log("\n"); } virtual void execute(std::vector<std::string> args, RTLIL::Design *design) { log_header(design, "Executing EXTRACT_REDUCE pass.\n"); log_push(); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { // if (args[argidx] == "-v") { // verbose = true; // continue; // } break; } extra_args(args, argidx, design); for (auto module : design->selected_modules()) { SigMap sigmap(module); // Index all of the nets in the module dict<SigBit, Cell*> sig_to_driver; dict<SigBit, pool<Cell*>> sig_to_sink; for (auto cell : module->selected_cells()) { for (auto &conn : cell->connections()) { if (cell->output(conn.first)) for (auto bit : sigmap(conn.second)) sig_to_driver[bit] = cell; if (cell->input(conn.first)) { for (auto bit : sigmap(conn.second)) { if (sig_to_sink.count(bit) == 0) sig_to_sink[bit] = pool<Cell*>(); sig_to_sink[bit].insert(cell); } } } } // Need to check if any wires connect to module ports pool<SigBit> port_sigs; for (auto wire : module->selected_wires()) if (wire->port_input || wire->port_output) for (auto bit : sigmap(wire)) port_sigs.insert(bit); // Actual logic starts here pool<Cell*> consumed_cells; for (auto cell : module->selected_cells()) { if (consumed_cells.count(cell)) continue; GateType gt; if (cell->type == "$_AND_") gt = GateType::And; else if (cell->type == "$_OR_") gt = GateType::Or; else if (cell->type == "$_XOR_") gt = GateType::Xor; else continue; log("Working on cell %s...\n", cell->name.c_str()); // Go all the way to the sink Cell* head_cell = cell; Cell* x = cell; while (true) { if (!((x->type == "$_AND_" && gt == GateType::And) || (x->type == "$_OR_" && gt == GateType::Or) || (x->type == "$_XOR_" && gt == GateType::Xor))) break; head_cell = x; auto y = sigmap(x->getPort("\\Y")); log_assert(y.size() == 1); // Should only continue if there is one fanout back into a cell (not to a port) if (sig_to_sink[y[0]].size() != 1) break; x = *sig_to_sink[y[0]].begin(); } log(" Head cell is %s\n", head_cell->name.c_str()); pool<Cell*> cur_supercell; std::deque<Cell*> bfs_queue = {head_cell}; while (bfs_queue.size()) { Cell* x = bfs_queue.front(); bfs_queue.pop_front(); cur_supercell.insert(x); auto a = sigmap(x->getPort("\\A")); log_assert(a.size() == 1); // Must have only one sink // XXX: Check that it is indeed this node? if (sig_to_sink[a[0]].size() + port_sigs.count(a[0]) == 1) { Cell* cell_a = sig_to_driver[a[0]]; if (cell_a && ((cell_a->type == "$_AND_" && gt == GateType::And) || (cell_a->type == "$_OR_" && gt == GateType::Or) || (cell_a->type == "$_XOR_" && gt == GateType::Xor))) { // The cell here is the correct type, and it's definitely driving only // this current cell. bfs_queue.push_back(cell_a); } } auto b = sigmap(x->getPort("\\B")); log_assert(b.size() == 1); // Must have only one sink // XXX: Check that it is indeed this node? if (sig_to_sink[b[0]].size() + port_sigs.count(b[0]) == 1) { Cell* cell_b = sig_to_driver[b[0]]; if (cell_b && ((cell_b->type == "$_AND_" && gt == GateType::And) || (cell_b->type == "$_OR_" && gt == GateType::Or) || (cell_b->type == "$_XOR_" && gt == GateType::Xor))) { // The cell here is the correct type, and it's definitely driving only // this current cell. bfs_queue.push_back(cell_b); } } } log(" Cells:\n"); for (auto x : cur_supercell) log(" %s\n", x->name.c_str()); if (cur_supercell.size() > 1) { // Worth it to create reduce cell log(" Creating $reduce_* cell!\n"); pool<SigBit> input_pool; pool<SigBit> input_pool_intermed; for (auto x : cur_supercell) { input_pool.insert(sigmap(x->getPort("\\A"))[0]); input_pool.insert(sigmap(x->getPort("\\B"))[0]); input_pool_intermed.insert(sigmap(x->getPort("\\Y"))[0]); } SigSpec input; for (auto b : input_pool) if (input_pool_intermed.count(b) == 0) input.append_bit(b); SigBit output = sigmap(head_cell->getPort("\\Y")[0]); auto new_reduce_cell = module->addCell(NEW_ID, gt == GateType::And ? "$reduce_and" : gt == GateType::Or ? "$reduce_or" : gt == GateType::Xor ? "$reduce_xor" : ""); new_reduce_cell->setParam("\\A_SIGNED", 0); new_reduce_cell->setParam("\\A_WIDTH", input.size()); new_reduce_cell->setParam("\\Y_WIDTH", 1); new_reduce_cell->setPort("\\A", input); new_reduce_cell->setPort("\\Y", output); for (auto x : cur_supercell) consumed_cells.insert(x); } } // Remove every cell that we've used up for (auto cell : consumed_cells) module->remove(cell); } log_pop(); } } ExtractReducePass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2012 Fernando Josรฉ Iglesias Garcรญa * Copyright (C) 2012 Fernando Josรฉ Iglesias Garcรญa */ #include <shogun/lib/common.h> #ifdef HAVE_EIGEN3 #include <shogun/multiclass/QDA.h> #include <shogun/machine/NativeMulticlassMachine.h> #include <shogun/features/Features.h> #include <shogun/labels/Labels.h> #include <shogun/labels/MulticlassLabels.h> #include <shogun/mathematics/Math.h> #include <shogun/mathematics/eigen3.h> using namespace Eigen; typedef Matrix< float64_t, Dynamic, Dynamic, ColMajor > EMatrix; typedef Matrix< float64_t, Dynamic, 1, ColMajor > EVector; typedef Array< float64_t, Dynamic, 1 > EArray; using namespace shogun; CQDA::CQDA(float64_t tolerance, bool store_covs) : CNativeMulticlassMachine(), m_tolerance(tolerance), m_store_covs(store_covs), m_num_classes(0), m_dim(0) { init(); } CQDA::CQDA(CDenseFeatures<float64_t>* traindat, CLabels* trainlab, float64_t tolerance, bool store_covs) : CNativeMulticlassMachine(), m_tolerance(tolerance), m_store_covs(store_covs), m_num_classes(0), m_dim(0) { init(); set_features(traindat); set_labels(trainlab); } CQDA::~CQDA() { SG_UNREF(m_features); cleanup(); } void CQDA::init() { SG_ADD(&m_tolerance, "m_tolerance", "Tolerance member.", MS_AVAILABLE); SG_ADD(&m_store_covs, "m_store_covs", "Store covariances member", MS_NOT_AVAILABLE); SG_ADD((CSGObject**) &m_features, "m_features", "Feature object.", MS_NOT_AVAILABLE); SG_ADD(&m_means, "m_means", "Mean vectors list", MS_NOT_AVAILABLE); SG_ADD(&m_slog, "m_slog", "Vector used in classification", MS_NOT_AVAILABLE); //TODO include SGNDArray objects for serialization m_features = NULL; } void CQDA::cleanup() { m_means=SGMatrix<float64_t>(); m_num_classes = 0; } CMulticlassLabels* CQDA::apply_multiclass(CFeatures* data) { if (data) { if (!data->has_property(FP_DOT)) SG_ERROR("Specified features are not of type CDotFeatures\n") set_features((CDotFeatures*) data); } if ( !m_features ) return NULL; int32_t num_vecs = m_features->get_num_vectors(); ASSERT(num_vecs > 0) ASSERT( m_dim == m_features->get_dim_feature_space() ) CDenseFeatures< float64_t >* rf = (CDenseFeatures< float64_t >*) m_features; EMatrix X(num_vecs, m_dim); EMatrix A(num_vecs, m_dim); EVector norm2(num_vecs*m_num_classes); norm2.setZero(); int32_t vlen; bool vfree; float64_t* vec; for (int k = 0; k < m_num_classes; k++) { // X = features - means for (int i = 0; i < num_vecs; i++) { vec = rf->get_feature_vector(i, vlen, vfree); ASSERT(vec) Eigen::Map< EVector > Evec(vec,vlen); Eigen::Map< EVector > Em_means_col(m_means.get_column_vector(k), m_dim); X.row(i) = Evec - Em_means_col; rf->free_feature_vector(vec, i, vfree); } Eigen::Map< EMatrix > Em_M(m_M.get_matrix(k), m_dim, m_dim); A = X*Em_M; for (int i = 0; i < num_vecs; i++) norm2(i + k*num_vecs) = A.row(i).array().square().sum(); #ifdef DEBUG_QDA SG_PRINT("\n>>> Displaying A ...\n") SGMatrix< float64_t >::display_matrix(A.data(), num_vecs, m_dim); #endif } for (int i = 0; i < num_vecs; i++) for (int k = 0; k < m_num_classes; k++) { norm2[i + k*num_vecs] += m_slog[k]; norm2[i + k*num_vecs] *= -0.5; } CMulticlassLabels* out = new CMulticlassLabels(num_vecs); for (int i = 0 ; i < num_vecs; i++) out->set_label(i, SGVector<float64_t>::arg_max(norm2.data()+i, num_vecs, m_num_classes)); #ifdef DEBUG_QDA SG_PRINT("\n>>> Displaying norm2 ...\n") SGMatrix< float64_t >::display_matrix(norm2.data(), num_vecs, m_num_classes); SG_PRINT("\n>>> Displaying out ...\n") SGVector< float64_t >::display_vector(out->get_labels().vector, num_vecs); #endif return out; } bool CQDA::train_machine(CFeatures* data) { if (!m_labels) SG_ERROR("No labels allocated in QDA training\n") if ( data ) { if (!data->has_property(FP_DOT)) SG_ERROR("Speficied features are not of type CDotFeatures\n") set_features((CDotFeatures*) data); } if (!m_features) SG_ERROR("No features allocated in QDA training\n") SGVector< int32_t > train_labels = ((CMulticlassLabels*) m_labels)->get_int_labels(); if (!train_labels.vector) SG_ERROR("No train_labels allocated in QDA training\n") cleanup(); m_num_classes = ((CMulticlassLabels*) m_labels)->get_num_classes(); m_dim = m_features->get_dim_feature_space(); int32_t num_vec = m_features->get_num_vectors(); if (num_vec != train_labels.vlen) SG_ERROR("Dimension mismatch between features and labels in QDA training") int32_t* class_idxs = SG_MALLOC(int32_t, num_vec*m_num_classes); // number of examples of each class int32_t* class_nums = SG_MALLOC(int32_t, m_num_classes); memset(class_nums, 0, m_num_classes*sizeof(int32_t)); int32_t class_idx; for (int i = 0; i < train_labels.vlen; i++) { class_idx = train_labels.vector[i]; if (class_idx < 0 || class_idx >= m_num_classes) { SG_ERROR("found label out of {0, 1, 2, ..., num_classes-1}...") return false; } else { class_idxs[ class_idx*num_vec + class_nums[class_idx]++ ] = i; } } for (int i = 0; i < m_num_classes; i++) { if (class_nums[i] <= 0) { SG_ERROR("What? One class with no elements\n") return false; } } if (m_store_covs) { // cov_dims will be free in m_covs.destroy_ndarray() index_t * cov_dims = SG_MALLOC(index_t, 3); cov_dims[0] = m_dim; cov_dims[1] = m_dim; cov_dims[2] = m_num_classes; m_covs = SGNDArray< float64_t >(cov_dims, 3); } m_means = SGMatrix< float64_t >(m_dim, m_num_classes, true); SGMatrix< float64_t > scalings = SGMatrix< float64_t >(m_dim, m_num_classes); // rot_dims will be freed in rotations.destroy_ndarray() index_t* rot_dims = SG_MALLOC(index_t, 3); rot_dims[0] = m_dim; rot_dims[1] = m_dim; rot_dims[2] = m_num_classes; SGNDArray< float64_t > rotations = SGNDArray< float64_t >(rot_dims, 3); CDenseFeatures< float64_t >* rf = (CDenseFeatures< float64_t >*) m_features; m_means.zero(); int32_t vlen; bool vfree; float64_t* vec; for (int k = 0; k < m_num_classes; k++) { EMatrix buffer(class_nums[k], m_dim); Eigen::Map< EVector > Em_means(m_means.get_column_vector(k), m_dim); for (int i = 0; i < class_nums[k]; i++) { vec = rf->get_feature_vector(class_idxs[k*num_vec + i], vlen, vfree); ASSERT(vec) Eigen::Map< EVector > Evec(vec, vlen); Em_means += Evec; buffer.row(i) = Evec; rf->free_feature_vector(vec, class_idxs[k*num_vec + i], vfree); } Em_means /= class_nums[k]; for (int i = 0; i < class_nums[k]; i++) buffer.row(i) -= Em_means; // SVD float64_t * col = scalings.get_column_vector(k); float64_t * rot_mat = rotations.get_matrix(k); Eigen::JacobiSVD<EMatrix> eSvd; eSvd.compute(buffer,Eigen::ComputeFullV); memcpy(col, eSvd.singularValues().data(), m_dim*sizeof(float64_t)); memcpy(rot_mat, eSvd.matrixV().data(), m_dim*m_dim*sizeof(float64_t)); SGVector<float64_t>::vector_multiply(col, col, col, m_dim); SGVector<float64_t>::scale_vector(1.0/(class_nums[k]-1), col, m_dim); rotations.transpose_matrix(k); if (m_store_covs) { Eigen::Map< EMatrix > EM(SGVector<float64_t>::clone_vector(rot_mat, m_dim*m_dim), m_dim, m_dim); Eigen::Map< EArray > Escalings(scalings.get_column_vector(k), m_dim); for (int i = 0; i < m_dim; i++) EM.row(i) = ( (EM.row(i).array()) * Escalings ).matrix(); Eigen::Map< EMatrix > Em_covs(m_covs.get_matrix(k), m_dim, m_dim); Eigen::Map< EMatrix > Erot_mat(rot_mat, m_dim, m_dim); Em_covs = EM*Erot_mat; } } /* Computation of terms required for classification */ SGVector< float32_t > sinvsqrt(m_dim); // M_dims will be freed in m_M.destroy_ndarray() index_t* M_dims = SG_MALLOC(index_t, 3); M_dims[0] = m_dim; M_dims[1] = m_dim; M_dims[2] = m_num_classes; m_M = SGNDArray< float64_t >(M_dims, 3); m_slog = SGVector< float32_t >(m_num_classes); m_slog.zero(); index_t idx = 0; for (int k = 0; k < m_num_classes; k++) { for (int j = 0; j < m_dim; j++) { sinvsqrt[j] = 1.0 / CMath::sqrt(scalings[k*m_dim + j]); m_slog[k] += CMath::log(scalings[k*m_dim + j]); } for (int i = 0; i < m_dim; i++) for (int j = 0; j < m_dim; j++) { idx = k*m_dim*m_dim + i + j*m_dim; m_M[idx] = rotations[idx] * sinvsqrt[j]; } } #ifdef DEBUG_QDA SG_PRINT(">>> QDA machine trained with %d classes\n", m_num_classes) SG_PRINT("\n>>> Displaying means ...\n") SGMatrix< float64_t >::display_matrix(m_means.matrix, m_dim, m_num_classes); SG_PRINT("\n>>> Displaying scalings ...\n") SGMatrix< float64_t >::display_matrix(scalings.matrix, m_dim, m_num_classes); SG_PRINT("\n>>> Displaying rotations ... \n") for (int k = 0; k < m_num_classes; k++) SGMatrix< float64_t >::display_matrix(rotations.get_matrix(k), m_dim, m_dim); SG_PRINT("\n>>> Displaying sinvsqrt ... \n") sinvsqrt.display_vector(); SG_PRINT("\n>>> Diplaying m_M matrices ... \n") for (int k = 0; k < m_num_classes; k++) SGMatrix< float64_t >::display_matrix(m_M.get_matrix(k), m_dim, m_dim); SG_PRINT("\n>>> Exit DEBUG_QDA\n") #endif SG_FREE(class_idxs); SG_FREE(class_nums); return true; } #endif /* HAVE_EIGEN3 */ <commit_msg>fixed crash in QDA covar calculation<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2012 Fernando Josรฉ Iglesias Garcรญa * Copyright (C) 2012 Fernando Josรฉ Iglesias Garcรญa */ #include <shogun/lib/common.h> #ifdef HAVE_EIGEN3 #include <shogun/multiclass/QDA.h> #include <shogun/machine/NativeMulticlassMachine.h> #include <shogun/features/Features.h> #include <shogun/labels/Labels.h> #include <shogun/labels/MulticlassLabels.h> #include <shogun/mathematics/Math.h> #include <shogun/mathematics/eigen3.h> using namespace Eigen; typedef Matrix< float64_t, Dynamic, Dynamic, ColMajor > EMatrix; typedef Matrix< float64_t, Dynamic, 1, ColMajor > EVector; typedef Array< float64_t, Dynamic, 1 > EArray; using namespace shogun; CQDA::CQDA(float64_t tolerance, bool store_covs) : CNativeMulticlassMachine(), m_tolerance(tolerance), m_store_covs(store_covs), m_num_classes(0), m_dim(0) { init(); } CQDA::CQDA(CDenseFeatures<float64_t>* traindat, CLabels* trainlab, float64_t tolerance, bool store_covs) : CNativeMulticlassMachine(), m_tolerance(tolerance), m_store_covs(store_covs), m_num_classes(0), m_dim(0) { init(); set_features(traindat); set_labels(trainlab); } CQDA::~CQDA() { SG_UNREF(m_features); cleanup(); } void CQDA::init() { SG_ADD(&m_tolerance, "m_tolerance", "Tolerance member.", MS_AVAILABLE); SG_ADD(&m_store_covs, "m_store_covs", "Store covariances member", MS_NOT_AVAILABLE); SG_ADD((CSGObject**) &m_features, "m_features", "Feature object.", MS_NOT_AVAILABLE); SG_ADD(&m_means, "m_means", "Mean vectors list", MS_NOT_AVAILABLE); SG_ADD(&m_slog, "m_slog", "Vector used in classification", MS_NOT_AVAILABLE); //TODO include SGNDArray objects for serialization m_features = NULL; } void CQDA::cleanup() { m_means=SGMatrix<float64_t>(); m_num_classes = 0; } CMulticlassLabels* CQDA::apply_multiclass(CFeatures* data) { if (data) { if (!data->has_property(FP_DOT)) SG_ERROR("Specified features are not of type CDotFeatures\n") set_features((CDotFeatures*) data); } if ( !m_features ) return NULL; int32_t num_vecs = m_features->get_num_vectors(); ASSERT(num_vecs > 0) ASSERT( m_dim == m_features->get_dim_feature_space() ) CDenseFeatures< float64_t >* rf = (CDenseFeatures< float64_t >*) m_features; EMatrix X(num_vecs, m_dim); EMatrix A(num_vecs, m_dim); EVector norm2(num_vecs*m_num_classes); norm2.setZero(); int32_t vlen; bool vfree; float64_t* vec; for (int k = 0; k < m_num_classes; k++) { // X = features - means for (int i = 0; i < num_vecs; i++) { vec = rf->get_feature_vector(i, vlen, vfree); ASSERT(vec) Eigen::Map< EVector > Evec(vec,vlen); Eigen::Map< EVector > Em_means_col(m_means.get_column_vector(k), m_dim); X.row(i) = Evec - Em_means_col; rf->free_feature_vector(vec, i, vfree); } Eigen::Map< EMatrix > Em_M(m_M.get_matrix(k), m_dim, m_dim); A = X*Em_M; for (int i = 0; i < num_vecs; i++) norm2(i + k*num_vecs) = A.row(i).array().square().sum(); #ifdef DEBUG_QDA SG_PRINT("\n>>> Displaying A ...\n") SGMatrix< float64_t >::display_matrix(A.data(), num_vecs, m_dim); #endif } for (int i = 0; i < num_vecs; i++) for (int k = 0; k < m_num_classes; k++) { norm2[i + k*num_vecs] += m_slog[k]; norm2[i + k*num_vecs] *= -0.5; } #ifdef DEBUG_QDA SG_PRINT("\n>>> Displaying norm2 ...\n") SGMatrix< float64_t >::display_matrix(norm2.data(), num_vecs, m_num_classes); #endif CMulticlassLabels* out = new CMulticlassLabels(num_vecs); for (int i = 0 ; i < num_vecs; i++) out->set_label(i, SGVector<float64_t>::arg_max(norm2.data()+i, num_vecs, m_num_classes)); return out; } bool CQDA::train_machine(CFeatures* data) { if (!m_labels) SG_ERROR("No labels allocated in QDA training\n") if ( data ) { if (!data->has_property(FP_DOT)) SG_ERROR("Speficied features are not of type CDotFeatures\n") set_features((CDotFeatures*) data); } if (!m_features) SG_ERROR("No features allocated in QDA training\n") SGVector< int32_t > train_labels = ((CMulticlassLabels*) m_labels)->get_int_labels(); if (!train_labels.vector) SG_ERROR("No train_labels allocated in QDA training\n") cleanup(); m_num_classes = ((CMulticlassLabels*) m_labels)->get_num_classes(); m_dim = m_features->get_dim_feature_space(); int32_t num_vec = m_features->get_num_vectors(); if (num_vec != train_labels.vlen) SG_ERROR("Dimension mismatch between features and labels in QDA training") int32_t* class_idxs = SG_MALLOC(int32_t, num_vec*m_num_classes); // number of examples of each class int32_t* class_nums = SG_MALLOC(int32_t, m_num_classes); memset(class_nums, 0, m_num_classes*sizeof(int32_t)); int32_t class_idx; for (int i = 0; i < train_labels.vlen; i++) { class_idx = train_labels.vector[i]; if (class_idx < 0 || class_idx >= m_num_classes) { SG_ERROR("found label out of {0, 1, 2, ..., num_classes-1}...") return false; } else { class_idxs[ class_idx*num_vec + class_nums[class_idx]++ ] = i; } } for (int i = 0; i < m_num_classes; i++) { if (class_nums[i] <= 0) { SG_ERROR("What? One class with no elements\n") return false; } } if (m_store_covs) { // cov_dims will be free in m_covs.destroy_ndarray() index_t * cov_dims = SG_MALLOC(index_t, 3); cov_dims[0] = m_dim; cov_dims[1] = m_dim; cov_dims[2] = m_num_classes; m_covs = SGNDArray< float64_t >(cov_dims, 3); } m_means = SGMatrix< float64_t >(m_dim, m_num_classes, true); SGMatrix< float64_t > scalings = SGMatrix< float64_t >(m_dim, m_num_classes); // rot_dims will be freed in rotations.destroy_ndarray() index_t* rot_dims = SG_MALLOC(index_t, 3); rot_dims[0] = m_dim; rot_dims[1] = m_dim; rot_dims[2] = m_num_classes; SGNDArray< float64_t > rotations = SGNDArray< float64_t >(rot_dims, 3); CDenseFeatures< float64_t >* rf = (CDenseFeatures< float64_t >*) m_features; m_means.zero(); int32_t vlen; bool vfree; float64_t* vec; for (int k = 0; k < m_num_classes; k++) { EMatrix buffer(class_nums[k], m_dim); Eigen::Map< EVector > Em_means(m_means.get_column_vector(k), m_dim); for (int i = 0; i < class_nums[k]; i++) { vec = rf->get_feature_vector(class_idxs[k*num_vec + i], vlen, vfree); ASSERT(vec) Eigen::Map< EVector > Evec(vec, vlen); Em_means += Evec; buffer.row(i) = Evec; rf->free_feature_vector(vec, class_idxs[k*num_vec + i], vfree); } Em_means /= class_nums[k]; for (int i = 0; i < class_nums[k]; i++) buffer.row(i) -= Em_means; // SVD float64_t * col = scalings.get_column_vector(k); float64_t * rot_mat = rotations.get_matrix(k); Eigen::JacobiSVD<EMatrix> eSvd; eSvd.compute(buffer,Eigen::ComputeFullV); memcpy(col, eSvd.singularValues().data(), m_dim*sizeof(float64_t)); memcpy(rot_mat, eSvd.matrixV().data(), m_dim*m_dim*sizeof(float64_t)); SGVector<float64_t>::vector_multiply(col, col, col, m_dim); SGVector<float64_t>::scale_vector(1.0/(class_nums[k]-1), col, m_dim); rotations.transpose_matrix(k); if (m_store_covs) { SGMatrix< float64_t > M(m_dim ,m_dim); EMatrix MEig = Map<EMatrix>(rot_mat,m_dim,m_dim); for (int i = 0; i < m_dim; i++) for (int j = 0; j < m_dim; j++) M(i,j)*=scalings[k*m_dim + j]; EMatrix rotE = Map<EMatrix>(rot_mat,m_dim,m_dim); EMatrix resE(m_dim,m_dim); resE = MEig * rotE.transpose(); memcpy(m_covs.get_matrix(k),resE.data(),m_dim*m_dim*sizeof(float64_t)); } } /* Computation of terms required for classification */ SGVector< float32_t > sinvsqrt(m_dim); // M_dims will be freed in m_M.destroy_ndarray() index_t* M_dims = SG_MALLOC(index_t, 3); M_dims[0] = m_dim; M_dims[1] = m_dim; M_dims[2] = m_num_classes; m_M = SGNDArray< float64_t >(M_dims, 3); m_slog = SGVector< float32_t >(m_num_classes); m_slog.zero(); index_t idx = 0; for (int k = 0; k < m_num_classes; k++) { for (int j = 0; j < m_dim; j++) { sinvsqrt[j] = 1.0 / CMath::sqrt(scalings[k*m_dim + j]); m_slog[k] += CMath::log(scalings[k*m_dim + j]); } for (int i = 0; i < m_dim; i++) for (int j = 0; j < m_dim; j++) { idx = k*m_dim*m_dim + i + j*m_dim; m_M[idx] = rotations[idx] * sinvsqrt[j]; } } #ifdef DEBUG_QDA SG_PRINT(">>> QDA machine trained with %d classes\n", m_num_classes) SG_PRINT("\n>>> Displaying means ...\n") SGMatrix< float64_t >::display_matrix(m_means.matrix, m_dim, m_num_classes); SG_PRINT("\n>>> Displaying scalings ...\n") SGMatrix< float64_t >::display_matrix(scalings.matrix, m_dim, m_num_classes); SG_PRINT("\n>>> Displaying rotations ... \n") for (int k = 0; k < m_num_classes; k++) SGMatrix< float64_t >::display_matrix(rotations.get_matrix(k), m_dim, m_dim); SG_PRINT("\n>>> Displaying sinvsqrt ... \n") sinvsqrt.display_vector(); SG_PRINT("\n>>> Diplaying m_M matrices ... \n") for (int k = 0; k < m_num_classes; k++) SGMatrix< float64_t >::display_matrix(m_M.get_matrix(k), m_dim, m_dim); SG_PRINT("\n>>> Exit DEBUG_QDA\n") #endif SG_FREE(class_idxs); SG_FREE(class_nums); return true; } #endif /* HAVE_EIGEN3 */ <|endoftext|>
<commit_before>/* * Ubitrack - Library for Ubiquitous Tracking * Copyright 2006, Technische Universitaet Muenchen, and individual * contributors as indicated by the @authors tag. See the * copyright.txt in the distribution for a full listing of individual * contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * @ingroup vision * @file * A class for encapsulating the image undistortion logic * * @author Daniel Pustka <daniel.pustka@in.tum.de> * @author Christian Waechter <christian.waechter@in.tum.de> (refactoring) */ #include "Undistortion.h" // OpenCV #include <opencv/cv.h> // Ubitrack #include "Image.h" #include <utUtil/CalibFile.h> #include <utUtil/Exception.h> #include "Util/OpenCV.h" // type conversion Ubitrack <-> OpenCV // get a logger #include <log4cpp/Category.hh> static log4cpp::Category& logger( log4cpp::Category::getInstance( "Ubitrack.Vision.Undistortion" ) ); namespace { /// scales the intrinsic camera matrix parameters to used image resolution template< typename PrecisionType > void inline correctForScale( const Ubitrack::Vision::Image& image, Ubitrack::Math::CameraIntrinsics< PrecisionType >& intrinsics ) { // scale the intrinsic matrix up or down if image size is different ( does not work if image is cropped instead of scaled) const PrecisionType scaleX = image.width / static_cast< PrecisionType > ( intrinsics.dimension( 0 ) ); intrinsics.matrix ( 0, 0 ) *= scaleX; intrinsics.matrix ( 0, 2 ) *= scaleX; intrinsics.dimension ( 0 ) *= scaleX; const PrecisionType scaleY = image.height / static_cast< PrecisionType > ( intrinsics.dimension( 1 ) ); intrinsics.matrix ( 1, 1 ) *= scaleY; intrinsics.matrix ( 1, 2 ) *= scaleY; intrinsics.dimension ( 1 ) *= scaleY; intrinsics.reset(); // recalculate the inverse } /// corrects the Ubitrack intrinsics matrix to the corresponding (left-handed) OpenCV camera matrix template< typename PrecisionType > void inline correctForOpenCV( Ubitrack::Math::CameraIntrinsics< PrecisionType >& intrinsics ) { // compensate for left-handed OpenCV coordinate frame intrinsics.matrix ( 0, 2 ) *= -1; intrinsics.matrix ( 1, 2 ) *= -1; intrinsics.matrix ( 2, 2 ) *= -1; intrinsics.reset(); // recalculate the inverse } /// corrects the Ubitrack intrinsics parameters if the image is flipped upside-down template< typename PrecisionType > void inline correctForOrigin( const Ubitrack::Vision::Image& image, Ubitrack::Math::CameraIntrinsics< PrecisionType >& intrinsics ) { if ( image.origin ) return; { // compensate if origin==0 intrinsics.matrix( 1, 2 ) = image.height - 1 - intrinsics.matrix( 1, 2 ); intrinsics.tangential_params( 1 ) *= -1.0; intrinsics.reset(); // recalculate the inverse } } } // anonymous namespace namespace Ubitrack { namespace Vision { Undistortion::Undistortion(){}; Undistortion::Undistortion( const std::string& intrinsicMatrixFile, const std::string& distortionFile ) { reset( intrinsicMatrixFile, distortionFile ); } Undistortion::Undistortion( const std::string& cameraIntrinsicsFile ) { reset( cameraIntrinsicsFile ); } Undistortion::Undistortion( const intrinsics_type& intrinsics ) { reset( intrinsics ); } void Undistortion::reset( const std::string& CameraIntrinsicsFile ) { Measurement::CameraIntrinsics measMat; measMat.reset( new intrinsics_type() ); Ubitrack::Util::readCalibFile( CameraIntrinsicsFile, measMat ); reset( *measMat ); } void Undistortion::reset( const intrinsics_type& camIntrinsics ) { m_intrinsics = camIntrinsics; m_intrinsicMatrix = m_intrinsics.matrix; m_coeffs( 0 ) = m_intrinsics.radial_params ( 0 ); m_coeffs( 1 ) = m_intrinsics.radial_params ( 1 ); m_coeffs( 2 ) = m_intrinsics.tangential_params ( 0 ); m_coeffs( 3 ) = m_intrinsics.tangential_params ( 1 ); for( std::size_t i = 4; i < (m_intrinsics.radial_size+2); ++i ) m_coeffs( i ) = m_intrinsics.radial_params( i-2 ); } void Undistortion::reset( const std::string& intrinsicMatrixFile, const std::string& distortionFile ) { // read intrinsics if ( !intrinsicMatrixFile.empty() ) { Measurement::Matrix3x3 measMat; measMat.reset( new Ubitrack::Math::Matrix< double, 3, 3 >() ); Ubitrack::Util::readCalibFile( intrinsicMatrixFile, measMat ); m_intrinsicMatrix = *measMat; LOG4CPP_DEBUG(logger, "Loaded calibration file : " << m_intrinsicMatrix); } else { m_intrinsicMatrix( 0, 0 ) = 400; m_intrinsicMatrix( 0, 1 ) = 0; m_intrinsicMatrix( 0, 2 ) = -160; m_intrinsicMatrix( 1, 0 ) = 0; m_intrinsicMatrix( 1, 1 ) = 400; m_intrinsicMatrix( 1, 2 ) = -120; m_intrinsicMatrix( 2, 0 ) = 0; m_intrinsicMatrix( 2, 1 ) = 0; m_intrinsicMatrix( 2, 2 ) = -1; } // initialize to zero m_coeffs = Ubitrack::Math::Vector< double, 8 >::zeros(); // read coefficients if ( !distortionFile.empty() ) { // first try new, eight element distortion file Measurement::Vector8D measVec; measVec.reset( new Ubitrack::Math::Vector< double, 8 >() ); try { Ubitrack::Util::readCalibFile( distortionFile, measVec ); m_coeffs = *measVec; } catch ( Ubitrack::Util::Exception ) { LOG4CPP_ERROR( logger, "Cannot read new image distortion model. Trying old format." ); // try old format, this time without exception handling Measurement::Vector4D measVec4D; measVec4D.reset( new Ubitrack::Math::Vector< double, 4 >() ); Ubitrack::Util::readCalibFile( distortionFile, measVec4D ); m_coeffs = Ubitrack::Math::Vector< double, 8 >::zeros(); boost::numeric::ublas::subrange( m_coeffs, 0, 4 ) = *measVec4D; } } { // set the intrinsics format from the old format intrinsics_type::radial_type radVec; radVec( 0 ) = m_coeffs( 0 ); radVec( 1 ) = m_coeffs( 1 ); radVec( 2 ) = m_coeffs( 4 ); radVec( 3 ) = m_coeffs( 5 ); radVec( 4 ) = m_coeffs( 6 ); radVec( 5 ) = m_coeffs( 7 ); intrinsics_type::tangential_type tanVec = intrinsics_type::tangential_type( m_coeffs( 2 ), m_coeffs( 3 ) ); m_intrinsics = intrinsics_type( m_intrinsicMatrix, radVec, tanVec ); } } /// resets the mapping to the provided image parameters bool Undistortion::resetMapping( const int width, const int height, const intrinsics_type& intrinsics ) { LOG4CPP_INFO( logger, "initialize undistortion mapping with intrinsics:\n" << intrinsics ); // reset the map images m_pMapX.reset( new Image( width, height, 1, IPL_DEPTH_32F ) ); m_pMapY.reset( new Image( width, height, 1, IPL_DEPTH_32F ) ); // copy the values to the corresponding opencv data-structures // CvMat cvIntrinsics; // CvMat cvCoeffs; CvMat* cvCoeffs = cvCreateMat( 1, intrinsics.radial_size + 2, CV_32FC1 ); CvMat* cvIntrinsics = cvCreateMat( 3, 3, CV_32FC1 ); Util::cv1::assign( intrinsics, *cvCoeffs, *cvIntrinsics ); // set values to the mapping cvInitUndistortMap( cvIntrinsics, cvCoeffs, *m_pMapX, *m_pMapY ); // explicitly release the allocated memory cvReleaseMat( &cvCoeffs ); cvReleaseMat( &cvIntrinsics ); // alternative undistortion using special fisheye calibration 8 camera should be really fishy, seems buggy in 2.4.11 (CW@2015-03-24) //cv::fisheye::initUndistortRectifyMap( cv::Mat( pCvIntrinsics ), cv::Mat( pCvCoeffs ), cv::Mat::eye( 3, 3, CV_32F ), cv::Mat::eye( 3, 3, CV_32F ), cv::Size( width, height ), CV_32FC1, cv::Mat( *m_pMapX ), cv::Mat( *m_pMapY ) ); LOG4CPP_INFO( logger, "Initialization of distortion maps finished." ); return true; } bool Undistortion::resetMapping( const Vision::Image& image ) { // generate a local copy first intrinsics_type camIntrinsics = m_intrinsics; // image size different than intrinsics ? -> scale correctForScale( image, camIntrinsics ); // always right-hand -> left-hand correctForOpenCV( camIntrinsics ); // upside down? -> flip intrinsics and tangential param correctForOrigin( image, camIntrinsics ); // set new lookup maps if( !resetMapping( image.width, image.height, camIntrinsics ) ) return false; return isValid( image ); } Vision::Image::Ptr Undistortion::undistort( Vision::Image::Ptr pImage ) { return undistort( *pImage ); } Vision::Image::Ptr Undistortion::undistort( const Image& image ) { // check if old values are still valid for the image size, only reset mapping if not if( !isValid( image ) ) if( !resetMapping( image ) ) return image.Clone(); // undistort Vision::Image::Ptr pImgUndistorted( new Image( image.width, image.height, image.nChannels, image.depth ) ); pImgUndistorted->origin = image.origin; cvRemap( image, *pImgUndistorted, *m_pMapX, *m_pMapY ); return pImgUndistorted; } bool Undistortion::isValid( const Vision::Image& image ) const { if ( !m_pMapX || !m_pMapY ) return false; if( m_pMapX->width != image.width || m_pMapX->height != image.height ) return false; if( m_pMapY->width != image.width || m_pMapY->height != image.height ) return false; return true; } } } // namespace Ubitrack::Vision <commit_msg>fix to undistortion to set channelSeq fields, which is required to transmit RGB images through the dataflow graph<commit_after>/* * Ubitrack - Library for Ubiquitous Tracking * Copyright 2006, Technische Universitaet Muenchen, and individual * contributors as indicated by the @authors tag. See the * copyright.txt in the distribution for a full listing of individual * contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * @ingroup vision * @file * A class for encapsulating the image undistortion logic * * @author Daniel Pustka <daniel.pustka@in.tum.de> * @author Christian Waechter <christian.waechter@in.tum.de> (refactoring) */ #include "Undistortion.h" // OpenCV #include <opencv/cv.h> // Ubitrack #include "Image.h" #include <utUtil/CalibFile.h> #include <utUtil/Exception.h> #include "Util/OpenCV.h" // type conversion Ubitrack <-> OpenCV // get a logger #include <log4cpp/Category.hh> static log4cpp::Category& logger( log4cpp::Category::getInstance( "Ubitrack.Vision.Undistortion" ) ); namespace { /// scales the intrinsic camera matrix parameters to used image resolution template< typename PrecisionType > void inline correctForScale( const Ubitrack::Vision::Image& image, Ubitrack::Math::CameraIntrinsics< PrecisionType >& intrinsics ) { // scale the intrinsic matrix up or down if image size is different ( does not work if image is cropped instead of scaled) const PrecisionType scaleX = image.width / static_cast< PrecisionType > ( intrinsics.dimension( 0 ) ); intrinsics.matrix ( 0, 0 ) *= scaleX; intrinsics.matrix ( 0, 2 ) *= scaleX; intrinsics.dimension ( 0 ) *= scaleX; const PrecisionType scaleY = image.height / static_cast< PrecisionType > ( intrinsics.dimension( 1 ) ); intrinsics.matrix ( 1, 1 ) *= scaleY; intrinsics.matrix ( 1, 2 ) *= scaleY; intrinsics.dimension ( 1 ) *= scaleY; intrinsics.reset(); // recalculate the inverse } /// corrects the Ubitrack intrinsics matrix to the corresponding (left-handed) OpenCV camera matrix template< typename PrecisionType > void inline correctForOpenCV( Ubitrack::Math::CameraIntrinsics< PrecisionType >& intrinsics ) { // compensate for left-handed OpenCV coordinate frame intrinsics.matrix ( 0, 2 ) *= -1; intrinsics.matrix ( 1, 2 ) *= -1; intrinsics.matrix ( 2, 2 ) *= -1; intrinsics.reset(); // recalculate the inverse } /// corrects the Ubitrack intrinsics parameters if the image is flipped upside-down template< typename PrecisionType > void inline correctForOrigin( const Ubitrack::Vision::Image& image, Ubitrack::Math::CameraIntrinsics< PrecisionType >& intrinsics ) { if ( image.origin ) return; { // compensate if origin==0 intrinsics.matrix( 1, 2 ) = image.height - 1 - intrinsics.matrix( 1, 2 ); intrinsics.tangential_params( 1 ) *= -1.0; intrinsics.reset(); // recalculate the inverse } } } // anonymous namespace namespace Ubitrack { namespace Vision { Undistortion::Undistortion(){}; Undistortion::Undistortion( const std::string& intrinsicMatrixFile, const std::string& distortionFile ) { reset( intrinsicMatrixFile, distortionFile ); } Undistortion::Undistortion( const std::string& cameraIntrinsicsFile ) { reset( cameraIntrinsicsFile ); } Undistortion::Undistortion( const intrinsics_type& intrinsics ) { reset( intrinsics ); } void Undistortion::reset( const std::string& CameraIntrinsicsFile ) { Measurement::CameraIntrinsics measMat; measMat.reset( new intrinsics_type() ); Ubitrack::Util::readCalibFile( CameraIntrinsicsFile, measMat ); reset( *measMat ); } void Undistortion::reset( const intrinsics_type& camIntrinsics ) { m_intrinsics = camIntrinsics; m_intrinsicMatrix = m_intrinsics.matrix; m_coeffs( 0 ) = m_intrinsics.radial_params ( 0 ); m_coeffs( 1 ) = m_intrinsics.radial_params ( 1 ); m_coeffs( 2 ) = m_intrinsics.tangential_params ( 0 ); m_coeffs( 3 ) = m_intrinsics.tangential_params ( 1 ); for( std::size_t i = 4; i < (m_intrinsics.radial_size+2); ++i ) m_coeffs( i ) = m_intrinsics.radial_params( i-2 ); } void Undistortion::reset( const std::string& intrinsicMatrixFile, const std::string& distortionFile ) { // read intrinsics if ( !intrinsicMatrixFile.empty() ) { Measurement::Matrix3x3 measMat; measMat.reset( new Ubitrack::Math::Matrix< double, 3, 3 >() ); Ubitrack::Util::readCalibFile( intrinsicMatrixFile, measMat ); m_intrinsicMatrix = *measMat; LOG4CPP_DEBUG(logger, "Loaded calibration file : " << m_intrinsicMatrix); } else { m_intrinsicMatrix( 0, 0 ) = 400; m_intrinsicMatrix( 0, 1 ) = 0; m_intrinsicMatrix( 0, 2 ) = -160; m_intrinsicMatrix( 1, 0 ) = 0; m_intrinsicMatrix( 1, 1 ) = 400; m_intrinsicMatrix( 1, 2 ) = -120; m_intrinsicMatrix( 2, 0 ) = 0; m_intrinsicMatrix( 2, 1 ) = 0; m_intrinsicMatrix( 2, 2 ) = -1; } // initialize to zero m_coeffs = Ubitrack::Math::Vector< double, 8 >::zeros(); // read coefficients if ( !distortionFile.empty() ) { // first try new, eight element distortion file Measurement::Vector8D measVec; measVec.reset( new Ubitrack::Math::Vector< double, 8 >() ); try { Ubitrack::Util::readCalibFile( distortionFile, measVec ); m_coeffs = *measVec; } catch ( Ubitrack::Util::Exception ) { LOG4CPP_ERROR( logger, "Cannot read new image distortion model. Trying old format." ); // try old format, this time without exception handling Measurement::Vector4D measVec4D; measVec4D.reset( new Ubitrack::Math::Vector< double, 4 >() ); Ubitrack::Util::readCalibFile( distortionFile, measVec4D ); m_coeffs = Ubitrack::Math::Vector< double, 8 >::zeros(); boost::numeric::ublas::subrange( m_coeffs, 0, 4 ) = *measVec4D; } } { // set the intrinsics format from the old format intrinsics_type::radial_type radVec; radVec( 0 ) = m_coeffs( 0 ); radVec( 1 ) = m_coeffs( 1 ); radVec( 2 ) = m_coeffs( 4 ); radVec( 3 ) = m_coeffs( 5 ); radVec( 4 ) = m_coeffs( 6 ); radVec( 5 ) = m_coeffs( 7 ); intrinsics_type::tangential_type tanVec = intrinsics_type::tangential_type( m_coeffs( 2 ), m_coeffs( 3 ) ); m_intrinsics = intrinsics_type( m_intrinsicMatrix, radVec, tanVec ); } } /// resets the mapping to the provided image parameters bool Undistortion::resetMapping( const int width, const int height, const intrinsics_type& intrinsics ) { LOG4CPP_INFO( logger, "initialize undistortion mapping with intrinsics:\n" << intrinsics ); // reset the map images m_pMapX.reset( new Image( width, height, 1, IPL_DEPTH_32F ) ); m_pMapY.reset( new Image( width, height, 1, IPL_DEPTH_32F ) ); // copy the values to the corresponding opencv data-structures // CvMat cvIntrinsics; // CvMat cvCoeffs; CvMat* cvCoeffs = cvCreateMat( 1, intrinsics.radial_size + 2, CV_32FC1 ); CvMat* cvIntrinsics = cvCreateMat( 3, 3, CV_32FC1 ); Util::cv1::assign( intrinsics, *cvCoeffs, *cvIntrinsics ); // set values to the mapping cvInitUndistortMap( cvIntrinsics, cvCoeffs, *m_pMapX, *m_pMapY ); // explicitly release the allocated memory cvReleaseMat( &cvCoeffs ); cvReleaseMat( &cvIntrinsics ); // alternative undistortion using special fisheye calibration 8 camera should be really fishy, seems buggy in 2.4.11 (CW@2015-03-24) //cv::fisheye::initUndistortRectifyMap( cv::Mat( pCvIntrinsics ), cv::Mat( pCvCoeffs ), cv::Mat::eye( 3, 3, CV_32F ), cv::Mat::eye( 3, 3, CV_32F ), cv::Size( width, height ), CV_32FC1, cv::Mat( *m_pMapX ), cv::Mat( *m_pMapY ) ); LOG4CPP_INFO( logger, "Initialization of distortion maps finished." ); return true; } bool Undistortion::resetMapping( const Vision::Image& image ) { // generate a local copy first intrinsics_type camIntrinsics = m_intrinsics; // image size different than intrinsics ? -> scale correctForScale( image, camIntrinsics ); // always right-hand -> left-hand correctForOpenCV( camIntrinsics ); // upside down? -> flip intrinsics and tangential param correctForOrigin( image, camIntrinsics ); // set new lookup maps if( !resetMapping( image.width, image.height, camIntrinsics ) ) return false; return isValid( image ); } Vision::Image::Ptr Undistortion::undistort( Vision::Image::Ptr pImage ) { return undistort( *pImage ); } Vision::Image::Ptr Undistortion::undistort( const Image& image ) { // check if old values are still valid for the image size, only reset mapping if not if( !isValid( image ) ) if( !resetMapping( image ) ) return image.Clone(); // undistort Vision::Image::Ptr pImgUndistorted( new Image( image.width, image.height, image.nChannels, image.depth ) ); pImgUndistorted->origin = image.origin; cvRemap( image, *pImgUndistorted, *m_pMapX, *m_pMapY ); pImgUndistorted->channelSeq[0] = image.channelSeq[0]; pImgUndistorted->channelSeq[1] = image.channelSeq[1]; pImgUndistorted->channelSeq[2] = image.channelSeq[2]; return pImgUndistorted; } bool Undistortion::isValid( const Vision::Image& image ) const { if ( !m_pMapX || !m_pMapY ) return false; if( m_pMapX->width != image.width || m_pMapX->height != image.height ) return false; if( m_pMapY->width != image.width || m_pMapY->height != image.height ) return false; return true; } } } // namespace Ubitrack::Vision <|endoftext|>
<commit_before>/** * @file system.hpp * Exact diagonaliser base classes. * @author Burkhard Ritter * @version * @date 2010-12-10 */ #ifndef __TEST_HPP__ #define __TEST_HPP__ #include <iostream> #include "basis.hpp" namespace Filter { class SelectAll { public: bool operator() (const State&) const {return true;} }; }; namespace Sorter { class DontSort { public: bool operator() (const State&, const State&) const {return false;} }; }; /** * Caching creator. * * Constructs one creator martrix for each orbital of the system and caches them. * * @tparam System */ template<class System> class Creator { public: Creator (const System& s_) : s(s_), cs(s.N_orbital) { for (size_t i=0; i<s.N_orbital; i++) constructMatrix(i); } const SMatrix& operator() (size_t i) const { return cs[i]; } private: void constructMatrix (size_t i) { cs[i] = SMatrix(s.basis.size(), s.basis.size()); // we expect one entry per column cs[i].reserve(s.basis.size()); for (size_t col=0; col<s.basis.size(); col++) { cs[i].startVec(col); if (s.basis(col)[i] == 1) continue; State state(s.basis(col)); state[i] = 1; const size_t row = s.basis(state); const size_t sum = state.count(i); const double sign = (sum%2==0)?1:-1; // probably faster than using (-1)^sum cs[i].insertBack(row, col) = sign; } cs[i].finalize(); } const System& s; std::vector<SMatrix> cs; }; template<class System> class Annihilator { public: Annihilator (const System& s_) : s(s_), as(s.N_orbital) { for (size_t i=0; i<s.N_orbital; i++) as[i] = SMatrix(s.creator(i).transpose()); } const SMatrix& operator() (size_t i) const { return as[i]; } private: const System& s; std::vector<SMatrix> as; }; template<class System> class Hamiltonian { public: Hamiltonian (const System& s_) : s(s_), H(s.basis.size(), s.basis.size()) {} /** * Construct the Hamiltonian matrix. * * Has to be overwritten by deriving classes. */ void construct() {} void diagonalise () { /* * This assertion is somewhat arbitrary, just because my computers tend * to have 4GB ~ 4 10^9 bytes of memory. * Also, this is not the solution for the problem. I don't understand * why Eigen gives a segfault instead of an exception. */ assert(4E9 > s.basis.size()*s.basis.size()*sizeof(double)); DMatrix m(H); SelfAdjointEigenSolver<DMatrix> es(m); eigenvalues = es.eigenvalues(); eigenvectors = es.eigenvectors(); Emin = eigenvalues.minCoeff(); } DMatrix eigenvectors; DVector eigenvalues; double Emin; protected: const System& s; SMatrix H; }; template<class System> class EnsembleAverage { public: EnsembleAverage (const System& s_) : s(s_) {} double operator() (double beta, const SMatrix& O) const { double sum = 0; for (int i=0; i<s.H.eigenvalues.size(); i++) sum += std::exp(-beta * (s.H.eigenvalues(i) - s.H.Emin)) * s.H.eigenvectors.col(i).adjoint() * O * s.H.eigenvectors.col(i); return sum / partitionFunction(beta); } double partitionFunction (double beta) const { double Z = 0; for (int i=0; i<s.H.eigenvalues.size(); i++) Z += std::exp(-beta * (s.H.eigenvalues(i) - s.H.Emin)); return Z; } private: const System& s; }; template<class Filter, class Sorter> class MinimalSystem { public: MinimalSystem (size_t N_orbital_, const Filter& filter, const Sorter& sorter) : N_orbital(N_orbital_), basis(N_orbital, filter, sorter) {} size_t N_orbital; Basis<Filter, Sorter> basis; }; template<class Filter, class Sorter> class BasicSystem : public MinimalSystem<Filter, Sorter> { public: BasicSystem (size_t N_orbital_, const Filter& filter, const Sorter& sorter) : MinimalSystem<Filter, Sorter>(N_orbital_, filter, sorter), creator(*this), annihilator(*this) {} Creator<BasicSystem> creator; Annihilator<BasicSystem> annihilator; }; /* template<class Filter, class Sorter> class System { public: System (size_t N_orbital_, const Filter& filter, const Sorter& sorter) : N_orbital(N_orbital_), basis(N_orbital, filter, sorter), creator(*this), annihilator(*this) {} size_t N_orbital; Basis<Filter, Sorter> basis; Creator<System> creator; Annihilator<System> annihilator; }; */ #endif // __TEST_HPP__ <commit_msg>Bit more documentation.<commit_after>/** * @file system.hpp * Exact diagonaliser base classes. * @author Burkhard Ritter * @version * @date 2010-12-10 */ #ifndef __TEST_HPP__ #define __TEST_HPP__ #include <iostream> #include "basis.hpp" /** * Filters to filter the basis states. */ namespace Filter { /** * Selects all states. * * Thus it's a filter that doesn't filter at all. It's the default Filter * used. */ class SelectAll { public: bool operator() (const State&) const {return true;} }; }; /** * Sorters to sort the basis states. */ namespace Sorter { /** * Does not sort the states. * * Thus it's a sorter that doesn't sort at all. It's the default Sorter * used. */ class DontSort { public: bool operator() (const State&, const State&) const {return false;} }; }; /** * Caching creator. * * Constructs one creator martrix for each orbital of the system and caches * them. * * @tparam System */ template<class System> class Creator { public: Creator (const System& s_) : s(s_), cs(s.N_orbital) { for (size_t i=0; i<s.N_orbital; i++) constructMatrix(i); } /** * Creator matrix for the given orbital. * * \f$c^{\dag}_i\f$ * * @param i orbital of the system * * @return */ const SMatrix& operator() (size_t i) const { return cs[i]; } private: void constructMatrix (size_t i) { cs[i] = SMatrix(s.basis.size(), s.basis.size()); // we expect one entry per column cs[i].reserve(s.basis.size()); for (size_t col=0; col<s.basis.size(); col++) { cs[i].startVec(col); if (s.basis(col)[i] == 1) continue; State state(s.basis(col)); state[i] = 1; const size_t row = s.basis(state); const size_t sum = state.count(i); const double sign = (sum%2==0)?1:-1; // probably faster than using (-1)^sum cs[i].insertBack(row, col) = sign; } cs[i].finalize(); } const System& s; std::vector<SMatrix> cs; }; /** * Caching annihilator. * * Constructs one annihilator matrix for each orbital of the system and caches * them. * * @tparam System */ template<class System> class Annihilator { public: Annihilator (const System& s_) : s(s_), as(s.N_orbital) { for (size_t i=0; i<s.N_orbital; i++) as[i] = SMatrix(s.creator(i).transpose()); } /** * Annihilator matrix for the given orbital. * * \f$c_i\f$ * * @param i orbital of the system * * @return */ const SMatrix& operator() (size_t i) const { return as[i]; } private: const System& s; std::vector<SMatrix> as; }; /** * Hamiltonian of the system. * * The heart of the fermionic quantum system. Although it is an * operator it behaves a little bit different than the other operators, which * maybe doesn't entirely come as a surprise. It is * not a function object. It has to be subclassed and * overwritten for each different physical system. Typical usage: * @code * Hamiltonian H(mySystem); * H.construct(); * H.diagonalise(); //here the real work happens * H.eigenvalues(); //use eigenenergies * @endcode * * @tparam System */ template<class System> class Hamiltonian { public: Hamiltonian (const System& s_) : s(s_), H(s.basis.size(), s.basis.size()) {} /** * Construct the Hamiltonian matrix. * * Has to be overwritten by deriving classes. */ void construct() {} /** * Diagonalises the Hamiltonian matrix. * * Uses a dense matrix. Relies on Eigen for the eigenvalue decomposition. */ void diagonalise () { /* * This assertion is somewhat arbitrary, just because my computers tend * to have 4GB ~ 4 10^9 bytes of memory. * Also, this is not the solution for the problem. I don't understand * why Eigen gives a segfault instead of an exception. */ assert(4E9 > s.basis.size()*s.basis.size()*sizeof(double)); DMatrix m(H); SelfAdjointEigenSolver<DMatrix> es(m); eigenvalues = es.eigenvalues(); eigenvectors = es.eigenvectors(); Emin = eigenvalues.minCoeff(); } DMatrix eigenvectors; DVector eigenvalues; double Emin; protected: const System& s; SMatrix H; }; /** * Calculate the ensemble average. * * An operator. Example usage: * @code * EnsembleAverage ensembleAverage(mySystem); * MyFunkyOperator O(mySystem); * ensembleAverage(beta, O); //will expect and use mySystem.H * @endcode * * Dependencies: System.basis and System.H (Hamiltonian) * * @tparam System */ template<class System> class EnsembleAverage { public: EnsembleAverage (const System& s_) : s(s_) {} /** * Calculate the ensemble average for the given operator. * * @param beta = 1/T (temperature) * @param O operator matrix * * @return */ double operator() (double beta, const SMatrix& O) const { double sum = 0; for (int i=0; i<s.H.eigenvalues.size(); i++) sum += std::exp(-beta * (s.H.eigenvalues(i) - s.H.Emin)) * s.H.eigenvectors.col(i).adjoint() * O * s.H.eigenvectors.col(i); return sum / partitionFunction(beta); } /** * Calculate the partition function at the given temperature. * * @param beta = 1/T (temperature) * * @return */ double partitionFunction (double beta) const { double Z = 0; for (int i=0; i<s.H.eigenvalues.size(); i++) Z += std::exp(-beta * (s.H.eigenvalues(i) - s.H.Emin)); return Z; } private: const System& s; }; /** * Minimal base class for a fermionic quantum system. * * Only contains the basis. Filter and Sorter are passed on to the basis * and are used to filter and sort the basis states. * * Typical usage is to subclass and specify a custom Hamiltonian (subclassed * from Hamiltonian) as mySystem.H and probably some observables of interest * (say the particle number) as well as the EnsembleAverage. * * @tparam Filter * @tparam Sorter */ template<class Filter, class Sorter> class MinimalSystem { public: /** * Construct the minimal system. * * @param N_orbital number of orbitals * @param filter filter to filter basis states * @param sorter sorter to sort basis states */ MinimalSystem (size_t N_orbital_, const Filter& filter, const Sorter& sorter) : N_orbital(N_orbital_), basis(N_orbital, filter, sorter) {} size_t N_orbital; Basis<Filter, Sorter> basis; }; /** * Basic base class for fermionic quantum systems. * * In addition to the basis the basic system conveniently defines creator and * annihilator. * * @tparam Filter * @tparam Sorter */ template<class Filter, class Sorter> class BasicSystem : public MinimalSystem<Filter, Sorter> { public: /** * Construct the basic system. * * @param N_orbital_ * @param filter * @param sorter */ BasicSystem (size_t N_orbital_, const Filter& filter, const Sorter& sorter) : MinimalSystem<Filter, Sorter>(N_orbital_, filter, sorter), creator(*this), annihilator(*this) {} Creator<BasicSystem> creator; Annihilator<BasicSystem> annihilator; }; #endif // __TEST_HPP__ <|endoftext|>
<commit_before>/************************************************************/ /* print_board_functions.cpp: some functions to plot boards */ /************************************************************/ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "class_drawpanel.h" #include "pcbnew.h" #include "class_board_design_settings.h" #include "pcbplot.h" #include "printout_controler.h" #include "colors_selection.h" #include "protos.h" static void Print_Module( WinEDA_DrawPanel* aPanel, wxDC* aDC, MODULE* aModule, int aDraw_mode, int aMasklayer, PRINT_PARAMETERS::DrillShapeOptT aDrillShapeOpt ); /** Function PrintPage * Used to print the board (on printer, or when creating SVF files). * Print the board, but only layers allowed by aPrintMaskLayer * @param aDC = the print device context * @param aPrint_Sheet_Ref = true to print frame references * @param aPrint_Sheet_Ref = a 32 bits mask: bit n = 1 -> layer n is printed * @param aPrintMirrorMode = true to plot mirrored * @param aData = a pointer to an optional data (NULL if not used) */ void WinEDA_DrawPanel::PrintPage( wxDC* aDC, bool aPrint_Sheet_Ref, int aPrintMaskLayer, bool aPrintMirrorMode, void * aData) { MODULE* Module; int drawmode = GR_COPY; DISPLAY_OPTIONS save_opt; TRACK* pt_piste; WinEDA_BasePcbFrame* frame = (WinEDA_BasePcbFrame*) m_Parent; BOARD* Pcb = frame->GetBoard(); PRINT_PARAMETERS * printParameters = (PRINT_PARAMETERS*) aData; // can be null PRINT_PARAMETERS::DrillShapeOptT drillShapeOpt = PRINT_PARAMETERS::FULL_DRILL_SHAPE; if( printParameters ) drillShapeOpt = printParameters->m_DrillShapeOpt; save_opt = DisplayOpt; if( aPrintMaskLayer & ALL_CU_LAYERS ) { DisplayOpt.DisplayPadFill = true; DisplayOpt.DisplayViaFill = true; } else { DisplayOpt.DisplayPadFill = false; DisplayOpt.DisplayViaFill = false; } frame->m_DisplayPadFill = DisplayOpt.DisplayPadFill; frame->m_DisplayViaFill = DisplayOpt.DisplayViaFill; frame->m_DisplayPadNum = DisplayOpt.DisplayPadNum = false; bool nctmp = frame->GetBoard()->IsElementVisible(NO_CONNECTS_VISIBLE); DisplayOpt.DisplayPadIsol = false; DisplayOpt.DisplayModEdge = FILLED; DisplayOpt.DisplayModText = FILLED; frame->m_DisplayPcbTrackFill = DisplayOpt.DisplayPcbTrackFill = FILLED; DisplayOpt.ShowTrackClearanceMode = DO_NOT_SHOW_CLEARANCE; DisplayOpt.DisplayDrawItems = FILLED; DisplayOpt.DisplayZonesMode = 0; DisplayOpt.DisplayNetNamesMode = 0; m_PrintIsMirrored = aPrintMirrorMode; // The OR mode is used in color mode, but be aware the backgroud *must be // BLACK. In the print page dialog, we first plrint in BLACK, and after // reprint in color, on the black "local" backgroud, in OR mode the black // print is not made before, only a white page is printed if( GetGRForceBlackPenState() == false ) drawmode = GR_OR; /* Print the pcb graphic items (texts, ...) */ GRSetDrawMode( aDC, drawmode ); for( BOARD_ITEM* item = Pcb->m_Drawings; item; item = item->Next() ) { switch( item->Type() ) { case TYPE_DRAWSEGMENT: case TYPE_COTATION: case TYPE_TEXTE: case TYPE_MIRE: if( ( ( 1 << item->GetLayer() ) & aPrintMaskLayer ) == 0 ) break; item->Draw( this, aDC, drawmode ); break; case TYPE_MARKER_PCB: default: break; } } /* Print tracks */ pt_piste = Pcb->m_Track; for( ; pt_piste != NULL; pt_piste = pt_piste->Next() ) { if( ( aPrintMaskLayer & pt_piste->ReturnMaskLayer() ) == 0 ) continue; if( pt_piste->Type() == TYPE_VIA ) /* VIA encountered. */ { int rayon = pt_piste->m_Width >> 1; int color = g_ColorsSettings.GetItemColor(VIAS_VISIBLE+pt_piste->m_Shape); GRSetDrawMode( aDC, drawmode ); GRFilledCircle( &m_ClipBox, aDC, pt_piste->m_Start.x, pt_piste->m_Start.y, rayon, 0, color, color ); } else pt_piste->Draw( this, aDC, drawmode ); } pt_piste = Pcb->m_Zone; for( ; pt_piste != NULL; pt_piste = pt_piste->Next() ) { if( ( aPrintMaskLayer & pt_piste->ReturnMaskLayer() ) == 0 ) continue; pt_piste->Draw( this, aDC, drawmode ); } /* Draw filled areas (i.e. zones) */ for( int ii = 0; ii < Pcb->GetAreaCount(); ii++ ) { ZONE_CONTAINER* zone = Pcb->GetArea( ii ); if( ( aPrintMaskLayer & ( 1 << zone->GetLayer() ) ) == 0 ) continue; zone->DrawFilledArea( this, aDC, drawmode ); } // Draw footprints, this is done at last in order to print the pad holes in // white (or g_DrawBgColor) after the tracks and zones Module = (MODULE*) Pcb->m_Modules; for( ; Module != NULL; Module = Module->Next() ) { Print_Module( this, aDC, Module, drawmode, aPrintMaskLayer, drillShapeOpt ); } /* Print via holes in bg color: Not sure it is good for buried or blind * vias */ if( drillShapeOpt != PRINT_PARAMETERS::NO_DRILL_SHAPE ) { pt_piste = Pcb->m_Track; int color = g_DrawBgColor; bool blackpenstate = GetGRForceBlackPenState(); GRForceBlackPen( false ); GRSetDrawMode( aDC, GR_COPY ); for( ; pt_piste != NULL; pt_piste = pt_piste->Next() ) { if( ( aPrintMaskLayer & pt_piste->ReturnMaskLayer() ) == 0 ) continue; if( pt_piste->Type() == TYPE_VIA ) /* VIA encountered. */ { int diameter; if( drillShapeOpt == PRINT_PARAMETERS::SMALL_DRILL_SHAPE ) diameter = min( SMALL_DRILL, pt_piste->GetDrillValue()); else diameter = pt_piste->GetDrillValue(); GRFilledCircle( &m_ClipBox, aDC, pt_piste->m_Start.x, pt_piste->m_Start.y, diameter/2, 0, color, color ); } } GRForceBlackPen( blackpenstate ); } if( aPrint_Sheet_Ref ) m_Parent->TraceWorkSheet( aDC, GetScreen(), 10 ); m_PrintIsMirrored = false; DisplayOpt = save_opt; frame->m_DisplayPcbTrackFill = DisplayOpt.DisplayPcbTrackFill; frame->m_DisplayPadFill = DisplayOpt.DisplayPadFill; frame->m_DisplayViaFill = DisplayOpt.DisplayViaFill; frame->m_DisplayPadNum = DisplayOpt.DisplayPadNum; frame->GetBoard()->SetElementVisibility(NO_CONNECTS_VISIBLE, nctmp); } static void Print_Module( WinEDA_DrawPanel* aPanel, wxDC* aDC, MODULE* aModule, int aDraw_mode, int aMasklayer, PRINT_PARAMETERS::DrillShapeOptT aDrillShapeOpt ) { D_PAD* pt_pad; EDA_BaseStruct* PtStruct; TEXTE_MODULE* TextMod; int mlayer; /* Print pads */ pt_pad = aModule->m_Pads; for( ; pt_pad != NULL; pt_pad = pt_pad->Next() ) { if( (pt_pad->m_Masque_Layer & aMasklayer ) == 0 ) continue; // Usually we draw pads in sketch mode on non copper layers: if( (aMasklayer & ALL_CU_LAYERS) == 0 ) { int tmp_fill = ( (WinEDA_BasePcbFrame*) aPanel->GetParent() )->m_DisplayPadFill; // Switch in sketch mode ( (WinEDA_BasePcbFrame*) aPanel->GetParent() )->m_DisplayPadFill = 0; pt_pad->Draw( aPanel, aDC, aDraw_mode ); ( (WinEDA_BasePcbFrame*) aPanel->GetParent() )->m_DisplayPadFill = tmp_fill; } else // on copper layer, draw pads according to current options { // Manage hole according to the print drill option wxSize drill_tmp = pt_pad->m_Drill; switch ( aDrillShapeOpt ) { case PRINT_PARAMETERS::NO_DRILL_SHAPE: pt_pad->m_Drill = wxSize(0,0); break; case PRINT_PARAMETERS::SMALL_DRILL_SHAPE: pt_pad->m_Drill.x = MIN(SMALL_DRILL,pt_pad->m_Drill.x); pt_pad->m_Drill.y = MIN(SMALL_DRILL,pt_pad->m_Drill.y); break; case PRINT_PARAMETERS::FULL_DRILL_SHAPE: // Do nothing break; } pt_pad->Draw( aPanel, aDC, aDraw_mode ); pt_pad->m_Drill = drill_tmp; } } /* Print footprint graphic shapes */ PtStruct = aModule->m_Drawings; mlayer = g_TabOneLayerMask[aModule->GetLayer()]; if( aModule->GetLayer() == LAYER_N_BACK ) mlayer = SILKSCREEN_LAYER_BACK; else if( aModule->GetLayer() == LAYER_N_FRONT ) mlayer = SILKSCREEN_LAYER_FRONT; if( mlayer & aMasklayer ) { if( !aModule->m_Reference->m_NoShow ) aModule->m_Reference->Draw( aPanel, aDC, aDraw_mode ); if( !aModule->m_Value->m_NoShow ) aModule->m_Value->Draw( aPanel, aDC, aDraw_mode ); } for( ; PtStruct != NULL; PtStruct = PtStruct->Next() ) { switch( PtStruct->Type() ) { case TYPE_TEXTE_MODULE: if( (mlayer & aMasklayer ) == 0 ) break; TextMod = (TEXTE_MODULE*) PtStruct; TextMod->Draw( aPanel, aDC, aDraw_mode ); break; case TYPE_EDGE_MODULE: { EDGE_MODULE* edge = (EDGE_MODULE*) PtStruct; if( ( g_TabOneLayerMask[edge->GetLayer()] & aMasklayer ) == 0 ) break; edge->Draw( aPanel, aDC, aDraw_mode ); break; } default: break; } } } <commit_msg>Pcbnew: removed the "no connect" mark when printing a board.<commit_after>/************************************************************/ /* print_board_functions.cpp: some functions to plot boards */ /************************************************************/ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "class_drawpanel.h" #include "pcbnew.h" #include "class_board_design_settings.h" #include "pcbplot.h" #include "printout_controler.h" #include "colors_selection.h" #include "protos.h" static void Print_Module( WinEDA_DrawPanel* aPanel, wxDC* aDC, MODULE* aModule, int aDraw_mode, int aMasklayer, PRINT_PARAMETERS::DrillShapeOptT aDrillShapeOpt ); /** Function PrintPage * Used to print the board (on printer, or when creating SVF files). * Print the board, but only layers allowed by aPrintMaskLayer * @param aDC = the print device context * @param aPrint_Sheet_Ref = true to print frame references * @param aPrint_Sheet_Ref = a 32 bits mask: bit n = 1 -> layer n is printed * @param aPrintMirrorMode = true to plot mirrored * @param aData = a pointer to an optional data (NULL if not used) */ void WinEDA_DrawPanel::PrintPage( wxDC* aDC, bool aPrint_Sheet_Ref, int aPrintMaskLayer, bool aPrintMirrorMode, void * aData) { MODULE* Module; int drawmode = GR_COPY; DISPLAY_OPTIONS save_opt; TRACK* pt_piste; WinEDA_BasePcbFrame* frame = (WinEDA_BasePcbFrame*) m_Parent; BOARD* Pcb = frame->GetBoard(); PRINT_PARAMETERS * printParameters = (PRINT_PARAMETERS*) aData; // can be null PRINT_PARAMETERS::DrillShapeOptT drillShapeOpt = PRINT_PARAMETERS::FULL_DRILL_SHAPE; if( printParameters ) drillShapeOpt = printParameters->m_DrillShapeOpt; save_opt = DisplayOpt; if( aPrintMaskLayer & ALL_CU_LAYERS ) { DisplayOpt.DisplayPadFill = true; DisplayOpt.DisplayViaFill = true; } else { DisplayOpt.DisplayPadFill = false; DisplayOpt.DisplayViaFill = false; } frame->m_DisplayPadFill = DisplayOpt.DisplayPadFill; frame->m_DisplayViaFill = DisplayOpt.DisplayViaFill; frame->m_DisplayPadNum = DisplayOpt.DisplayPadNum = false; bool nctmp = frame->GetBoard()->IsElementVisible(NO_CONNECTS_VISIBLE); frame->GetBoard()->SetElementVisibility(NO_CONNECTS_VISIBLE, false); DisplayOpt.DisplayPadIsol = false; DisplayOpt.DisplayModEdge = FILLED; DisplayOpt.DisplayModText = FILLED; frame->m_DisplayPcbTrackFill = DisplayOpt.DisplayPcbTrackFill = FILLED; DisplayOpt.ShowTrackClearanceMode = DO_NOT_SHOW_CLEARANCE; DisplayOpt.DisplayDrawItems = FILLED; DisplayOpt.DisplayZonesMode = 0; DisplayOpt.DisplayNetNamesMode = 0; m_PrintIsMirrored = aPrintMirrorMode; // The OR mode is used in color mode, but be aware the backgroud *must be // BLACK. In the print page dialog, we first plrint in BLACK, and after // reprint in color, on the black "local" backgroud, in OR mode the black // print is not made before, only a white page is printed if( GetGRForceBlackPenState() == false ) drawmode = GR_OR; /* Print the pcb graphic items (texts, ...) */ GRSetDrawMode( aDC, drawmode ); for( BOARD_ITEM* item = Pcb->m_Drawings; item; item = item->Next() ) { switch( item->Type() ) { case TYPE_DRAWSEGMENT: case TYPE_COTATION: case TYPE_TEXTE: case TYPE_MIRE: if( ( ( 1 << item->GetLayer() ) & aPrintMaskLayer ) == 0 ) break; item->Draw( this, aDC, drawmode ); break; case TYPE_MARKER_PCB: default: break; } } /* Print tracks */ pt_piste = Pcb->m_Track; for( ; pt_piste != NULL; pt_piste = pt_piste->Next() ) { if( ( aPrintMaskLayer & pt_piste->ReturnMaskLayer() ) == 0 ) continue; if( pt_piste->Type() == TYPE_VIA ) /* VIA encountered. */ { int rayon = pt_piste->m_Width >> 1; int color = g_ColorsSettings.GetItemColor(VIAS_VISIBLE+pt_piste->m_Shape); GRSetDrawMode( aDC, drawmode ); GRFilledCircle( &m_ClipBox, aDC, pt_piste->m_Start.x, pt_piste->m_Start.y, rayon, 0, color, color ); } else pt_piste->Draw( this, aDC, drawmode ); } pt_piste = Pcb->m_Zone; for( ; pt_piste != NULL; pt_piste = pt_piste->Next() ) { if( ( aPrintMaskLayer & pt_piste->ReturnMaskLayer() ) == 0 ) continue; pt_piste->Draw( this, aDC, drawmode ); } /* Draw filled areas (i.e. zones) */ for( int ii = 0; ii < Pcb->GetAreaCount(); ii++ ) { ZONE_CONTAINER* zone = Pcb->GetArea( ii ); if( ( aPrintMaskLayer & ( 1 << zone->GetLayer() ) ) == 0 ) continue; zone->DrawFilledArea( this, aDC, drawmode ); } // Draw footprints, this is done at last in order to print the pad holes in // white (or g_DrawBgColor) after the tracks and zones Module = (MODULE*) Pcb->m_Modules; for( ; Module != NULL; Module = Module->Next() ) { Print_Module( this, aDC, Module, drawmode, aPrintMaskLayer, drillShapeOpt ); } /* Print via holes in bg color: Not sure it is good for buried or blind * vias */ if( drillShapeOpt != PRINT_PARAMETERS::NO_DRILL_SHAPE ) { pt_piste = Pcb->m_Track; int color = g_DrawBgColor; bool blackpenstate = GetGRForceBlackPenState(); GRForceBlackPen( false ); GRSetDrawMode( aDC, GR_COPY ); for( ; pt_piste != NULL; pt_piste = pt_piste->Next() ) { if( ( aPrintMaskLayer & pt_piste->ReturnMaskLayer() ) == 0 ) continue; if( pt_piste->Type() == TYPE_VIA ) /* VIA encountered. */ { int diameter; if( drillShapeOpt == PRINT_PARAMETERS::SMALL_DRILL_SHAPE ) diameter = min( SMALL_DRILL, pt_piste->GetDrillValue()); else diameter = pt_piste->GetDrillValue(); GRFilledCircle( &m_ClipBox, aDC, pt_piste->m_Start.x, pt_piste->m_Start.y, diameter/2, 0, color, color ); } } GRForceBlackPen( blackpenstate ); } if( aPrint_Sheet_Ref ) m_Parent->TraceWorkSheet( aDC, GetScreen(), 10 ); m_PrintIsMirrored = false; DisplayOpt = save_opt; frame->m_DisplayPcbTrackFill = DisplayOpt.DisplayPcbTrackFill; frame->m_DisplayPadFill = DisplayOpt.DisplayPadFill; frame->m_DisplayViaFill = DisplayOpt.DisplayViaFill; frame->m_DisplayPadNum = DisplayOpt.DisplayPadNum; frame->GetBoard()->SetElementVisibility(NO_CONNECTS_VISIBLE, nctmp); } static void Print_Module( WinEDA_DrawPanel* aPanel, wxDC* aDC, MODULE* aModule, int aDraw_mode, int aMasklayer, PRINT_PARAMETERS::DrillShapeOptT aDrillShapeOpt ) { D_PAD* pt_pad; EDA_BaseStruct* PtStruct; TEXTE_MODULE* TextMod; int mlayer; /* Print pads */ pt_pad = aModule->m_Pads; for( ; pt_pad != NULL; pt_pad = pt_pad->Next() ) { if( (pt_pad->m_Masque_Layer & aMasklayer ) == 0 ) continue; // Usually we draw pads in sketch mode on non copper layers: if( (aMasklayer & ALL_CU_LAYERS) == 0 ) { int tmp_fill = ( (WinEDA_BasePcbFrame*) aPanel->GetParent() )->m_DisplayPadFill; // Switch in sketch mode ( (WinEDA_BasePcbFrame*) aPanel->GetParent() )->m_DisplayPadFill = 0; pt_pad->Draw( aPanel, aDC, aDraw_mode ); ( (WinEDA_BasePcbFrame*) aPanel->GetParent() )->m_DisplayPadFill = tmp_fill; } else // on copper layer, draw pads according to current options { // Manage hole according to the print drill option wxSize drill_tmp = pt_pad->m_Drill; switch ( aDrillShapeOpt ) { case PRINT_PARAMETERS::NO_DRILL_SHAPE: pt_pad->m_Drill = wxSize(0,0); break; case PRINT_PARAMETERS::SMALL_DRILL_SHAPE: pt_pad->m_Drill.x = MIN(SMALL_DRILL,pt_pad->m_Drill.x); pt_pad->m_Drill.y = MIN(SMALL_DRILL,pt_pad->m_Drill.y); break; case PRINT_PARAMETERS::FULL_DRILL_SHAPE: // Do nothing break; } pt_pad->Draw( aPanel, aDC, aDraw_mode ); pt_pad->m_Drill = drill_tmp; } } /* Print footprint graphic shapes */ PtStruct = aModule->m_Drawings; mlayer = g_TabOneLayerMask[aModule->GetLayer()]; if( aModule->GetLayer() == LAYER_N_BACK ) mlayer = SILKSCREEN_LAYER_BACK; else if( aModule->GetLayer() == LAYER_N_FRONT ) mlayer = SILKSCREEN_LAYER_FRONT; if( mlayer & aMasklayer ) { if( !aModule->m_Reference->m_NoShow ) aModule->m_Reference->Draw( aPanel, aDC, aDraw_mode ); if( !aModule->m_Value->m_NoShow ) aModule->m_Value->Draw( aPanel, aDC, aDraw_mode ); } for( ; PtStruct != NULL; PtStruct = PtStruct->Next() ) { switch( PtStruct->Type() ) { case TYPE_TEXTE_MODULE: if( (mlayer & aMasklayer ) == 0 ) break; TextMod = (TEXTE_MODULE*) PtStruct; TextMod->Draw( aPanel, aDC, aDraw_mode ); break; case TYPE_EDGE_MODULE: { EDGE_MODULE* edge = (EDGE_MODULE*) PtStruct; if( ( g_TabOneLayerMask[edge->GetLayer()] & aMasklayer ) == 0 ) break; edge->Draw( aPanel, aDC, aDraw_mode ); break; } default: break; } } } <|endoftext|>
<commit_before>// // ofxFBXSkeleton.cpp // ofxFBX-Example-Importer // // Created by Nick Hardeman on 11/5/13. // // #include "ofxFBXSkeleton.h" ofxFBXBone dummyBone; //-------------------------------------------------------------- ofxFBXSkeleton::ofxFBXSkeleton() { numBones = 0; } //-------------------------------------------------------------- ofxFBXSkeleton::~ofxFBXSkeleton() { } //-------------------------------------------------------------- void ofxFBXSkeleton::setup( FbxNode *pNode ) { ofxFBXNode::setup( pNode ); } //-------------------------------------------------------------- void ofxFBXSkeleton::reconstructNodeParenting() { map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; if( bone->parentBoneName == "" ) continue; // ofxFBXBone* pbone = getBone( bone->parentBoneName ); // if( bone->parentBoneName == "Armature|FootIK.L" || bone->parentBoneName == "Armature|FootIK.R" ) { // cout << "removing parent with name " << bone->parentBoneName << endl; // bone->clearParent( false ); // } // // if( pbone == NULL ) continue; // // cout << "reconstructNodeParenting :: " << bone->getName() << " parent: " << bone->parentBoneName << endl; // // if( bone->getParent() != NULL ) { // bone->clearParent( false ); // } // // bone->setParent( *pbone, false ); // bone->setGlobalPosition( bone->origNode.getGlobalPosition() ); // bone->setGlobalOrientation( bone->origNode.getGlobalOrientation() ); } } //-------------------------------------------------------------- void ofxFBXSkeleton::update( FbxTime& pTime, FbxPose* pPose ) { updateBoneProperties(); // map<string, ofxFBXBone >::iterator it; // for(it = bones.begin(); it != bones.end(); ++it ) { // ofxFBXBone* bone = &it->second; // ofxFBXBone* sbone = getSourceBone( it->first ); // if( sbone != NULL ) { // if( bone->isExternalControlEnabled() ) { // sbone->enableExternalControl(); // } else { // sbone->disableExternalControl(); // } // // if( bone->isAnimationEnabled() ) { // sbone->enableAnimation(); // } else { // sbone->disableAnimation(); // } // } // } map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; ofxFBXBone* sbone = getSourceBone( it->first ); if( sbone != NULL ) { sbone->update( pTime, pPose ); } } for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; ofxFBXBone* sbone = getSourceBone( it->first ); if( sbone != NULL ) { bone->setTransformMatrix( sbone->getLocalTransformMatrix() ); } } } //-------------------------------------------------------------- void ofxFBXSkeleton::lateUpdate() { map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; ofxFBXBone* sbone = getSourceBone( it->first ); if( sbone != NULL ) { sbone->setGlobalOrientation( bone->getGlobalOrientation() ); sbone->setGlobalPosition( bone->getGlobalPosition() ); } } for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; ofxFBXBone* sbone = getSourceBone( it->first ); if( sbone != NULL ) { sbone->updateFbxTransform(); } } } //-------------------------------------------------------------- void ofxFBXSkeleton::updateWithAnimation( FbxTime& pTime, FbxPose* pPose ) { updateBoneProperties(); // map<string, ofxFBXBone >::iterator it; // for(it = bones.begin(); it != bones.end(); ++it ) { // ofxFBXBone* bone = &it->second; // ofxFBXBone* sbone = getSourceBone( it->first ); // if( sbone != NULL ) { // if( bone->isExternalControlEnabled() ) { // sbone->enableExternalControl(); // } else { // sbone->disableExternalControl(); // } // // if( bone->isAnimationEnabled() ) { // sbone->enableAnimation(); // } else { // sbone->disableAnimation(); // } // } // } map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; ofxFBXBone* sbone = getSourceBone( it->first ); if( sbone != NULL ) { sbone->update( pTime, pPose ); bone->setTransformMatrix( sbone->getLocalTransformMatrix() ); } } } //-------------------------------------------------------------- void ofxFBXSkeleton::lateUpdateWithAnimation() { map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; ofxFBXBone* sbone = getSourceBone( it->first ); if( sbone != NULL ) { // sbone->setTransformMatrix( bone->getLocalTransformMatrix() ); sbone->localTransformMatrix = bone->localTransformMatrix; sbone->setPosition( bone->getPosition() ); sbone->setOrientation( bone->getOrientationQuat() ); sbone->setScale( bone->getScale() ); } } for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; ofxFBXBone* sbone = getSourceBone( it->first ); if( sbone != NULL ) { sbone->updateFbxTransform(); } } } //-------------------------------------------------------------- void ofxFBXSkeleton::updateFromCachedSkeleton( shared_ptr< ofxFBXSkeleton> aSkeleton ) { // updateBoneProperties(); map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; // ofxFBXBone* sbone = getSourceBone( it->first ); // ofxFBXBone* sbone = aSkeleton->getSourceBone( it->first ); ofxFBXBone* obone = aSkeleton->getBone( it->first ); if( obone != NULL ) { // // localTransformMatrix = m44; // // ofQuaternion so; // localTransformMatrix.decompose(position, orientation, scale, so); // // onPositionChanged(); // onOrientationChanged(); // onScaleChanged(); // sbone->update( pTime, NULL ); // bone->setTransformMatrix( obone->getLocalTransformMatrix() ); bone->localTransformMatrix = obone->localTransformMatrix; bone->setPosition( obone->getPosition() ); bone->setOrientation( obone->getOrientationQuat() ); bone->setScale( obone->getScale() ); } else { ofLogWarning() << "updateFromCachedSkeleton: " << it->first << " is null !!" << endl; } } } //-------------------------------------------------------------- void ofxFBXSkeleton::updateBoneProperties() { map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; ofxFBXBone* sbone = getSourceBone( it->first ); if( sbone != NULL ) { if( bone->isExternalControlEnabled() ) { sbone->enableExternalControl(); } else { sbone->disableExternalControl(); } if( bone->isAnimationEnabled() ) { sbone->enableAnimation(); } else { sbone->disableAnimation(); } } } } //-------------------------------------------------------------- void ofxFBXSkeleton::draw( float aLen ) { map<string, ofxFBXBone>::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { it->second.draw(aLen); } } //-------------------------------------------------------------- void ofxFBXSkeleton::addBone( string aName, ofxFBXBone* aBone ) { if(aName == "") { ofLogWarning("ofxFBXSkeleton :: addBone : name is empty, not adding bone"); return; } if(bones.find(aName) != bones.end()) { // the bone has a duplicate name, try to make a unique key // aName += ofToString(numBones,0); } vector <string> strs;// = ofSplitString(aName, ":"); ofxFBXBone tbone = *aBone; string newBoneName = aName; if(strs.size() > 1) { newBoneName = strs[1]; } // cout << "adding a bone with name -" << newBoneName << "- parent name -" << getName() <<"-" << endl; sourceBones[ newBoneName ] = aBone; bones[ newBoneName ] = tbone; // cout << "ofxFBXSkeleton :: addBone : name: " << aName << " ptr parent = " << aBone->getParent() << " other: " << tbone.getParent() << endl; numBones++; } //-------------------------------------------------------------- ofxFBXBone* ofxFBXSkeleton::getBone( string aName ) { if(bones.find(aName) != bones.end()) { return &bones[ aName ]; } cout << "did not find the bone with name: " << aName << " | " << ofGetElapsedTimef() << endl; return NULL; } //-------------------------------------------------------------- ofxFBXBone* ofxFBXSkeleton::getSourceBone( string aName ) { if(bones.find(aName) != bones.end()) { return sourceBones[ aName ]; } return NULL; } //-------------------------------------------------------------- void ofxFBXSkeleton::enableExternalControl( string aName ) { // loop through hierarchy to make children also controlled externally ofxFBXBone* bone = getBone( aName ); if(bone == NULL) { ofLogWarning("ofxFBXSkeleton :: enableExternalControl : can not find bone with name ") << aName; return; } bone->enableExternalControl(); enableExternalControlRecursive( getSourceBone(aName) ); } //-------------------------------------------------------------- void ofxFBXSkeleton::enableExternalControlRecursive( ofxFBXBone* aBone ) { if( aBone == NULL ) return; map<string, ofxFBXBone* >::iterator it; for(it = sourceBones.begin(); it != sourceBones.end(); ++it ) { if( it->second->fbxNode->GetParent() == aBone->fbxNode ) { // it->second->enableExternalControl(); getBone( it->first )->enableExternalControl(); enableExternalControlRecursive( it->second ); } } } //-------------------------------------------------------------- void ofxFBXSkeleton::enableAnimation() { map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { it->second.enableAnimation(); } } //-------------------------------------------------------------- void ofxFBXSkeleton::disableAnimation() { map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { it->second.disableAnimation(); } } //-------------------------------------------------------------- int ofxFBXSkeleton::getNumBones() { return (int)bones.size(); } //-------------------------------------------------------------- void ofxFBXSkeleton::reset() { map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { it->second.reset(); } } //-------------------------------------------------------------- string ofxFBXSkeleton::toString() { map<string, ofxFBXBone >::iterator it; map< string, bool > printMap; for(it = bones.begin(); it != bones.end(); ++it ) { printMap[ it->first ] = false; } stringstream ss; ss << "Skeleton: " << getName() << " - Number of bones: " << bones.size() << endl; if( bones.size() ) { printOutBoneRecursive(ss, sourceBones.begin()->first, printMap, "" ); } else { ss << "NO BONES" << endl; } return ss.str().c_str(); } //-------------------------------------------------------------- void ofxFBXSkeleton::printOutBoneRecursive( stringstream& aSS, string aBoneName, map< string, bool >& aPrintMap, string aSpacer ) { if( aPrintMap[ aBoneName ] ) return; aPrintMap[ aBoneName ] = true; ofxFBXBone* bone = getSourceBone( aBoneName ); if( bone == NULL ) return; aSS << aSpacer << " bone: " << aBoneName << " parent: " << bone->parentBoneName << endl; aSpacer += "---"; map<string, ofxFBXBone*>::iterator it; for(it = sourceBones.begin(); it != sourceBones.end(); ++it ) { if( it->second->fbxNode->GetParent() == bone->fbxNode ) { printOutBoneRecursive( aSS, it->first, aPrintMap, aSpacer ); } } } <commit_msg>fix for node private member<commit_after>// // ofxFBXSkeleton.cpp // ofxFBX-Example-Importer // // Created by Nick Hardeman on 11/5/13. // // #include "ofxFBXSkeleton.h" ofxFBXBone dummyBone; //-------------------------------------------------------------- ofxFBXSkeleton::ofxFBXSkeleton() { numBones = 0; } //-------------------------------------------------------------- ofxFBXSkeleton::~ofxFBXSkeleton() { } //-------------------------------------------------------------- void ofxFBXSkeleton::setup( FbxNode *pNode ) { ofxFBXNode::setup( pNode ); } //-------------------------------------------------------------- void ofxFBXSkeleton::reconstructNodeParenting() { map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; if( bone->parentBoneName == "" ) continue; // ofxFBXBone* pbone = getBone( bone->parentBoneName ); // if( bone->parentBoneName == "Armature|FootIK.L" || bone->parentBoneName == "Armature|FootIK.R" ) { // cout << "removing parent with name " << bone->parentBoneName << endl; // bone->clearParent( false ); // } // // if( pbone == NULL ) continue; // // cout << "reconstructNodeParenting :: " << bone->getName() << " parent: " << bone->parentBoneName << endl; // // if( bone->getParent() != NULL ) { // bone->clearParent( false ); // } // // bone->setParent( *pbone, false ); // bone->setGlobalPosition( bone->origNode.getGlobalPosition() ); // bone->setGlobalOrientation( bone->origNode.getGlobalOrientation() ); } } //-------------------------------------------------------------- void ofxFBXSkeleton::update( FbxTime& pTime, FbxPose* pPose ) { updateBoneProperties(); // map<string, ofxFBXBone >::iterator it; // for(it = bones.begin(); it != bones.end(); ++it ) { // ofxFBXBone* bone = &it->second; // ofxFBXBone* sbone = getSourceBone( it->first ); // if( sbone != NULL ) { // if( bone->isExternalControlEnabled() ) { // sbone->enableExternalControl(); // } else { // sbone->disableExternalControl(); // } // // if( bone->isAnimationEnabled() ) { // sbone->enableAnimation(); // } else { // sbone->disableAnimation(); // } // } // } map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; ofxFBXBone* sbone = getSourceBone( it->first ); if( sbone != NULL ) { sbone->update( pTime, pPose ); } } for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; ofxFBXBone* sbone = getSourceBone( it->first ); if( sbone != NULL ) { bone->setTransformMatrix( sbone->getLocalTransformMatrix() ); } } } //-------------------------------------------------------------- void ofxFBXSkeleton::lateUpdate() { map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; ofxFBXBone* sbone = getSourceBone( it->first ); if( sbone != NULL ) { sbone->setGlobalOrientation( bone->getGlobalOrientation() ); sbone->setGlobalPosition( bone->getGlobalPosition() ); } } for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; ofxFBXBone* sbone = getSourceBone( it->first ); if( sbone != NULL ) { sbone->updateFbxTransform(); } } } //-------------------------------------------------------------- void ofxFBXSkeleton::updateWithAnimation( FbxTime& pTime, FbxPose* pPose ) { updateBoneProperties(); // map<string, ofxFBXBone >::iterator it; // for(it = bones.begin(); it != bones.end(); ++it ) { // ofxFBXBone* bone = &it->second; // ofxFBXBone* sbone = getSourceBone( it->first ); // if( sbone != NULL ) { // if( bone->isExternalControlEnabled() ) { // sbone->enableExternalControl(); // } else { // sbone->disableExternalControl(); // } // // if( bone->isAnimationEnabled() ) { // sbone->enableAnimation(); // } else { // sbone->disableAnimation(); // } // } // } map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; ofxFBXBone* sbone = getSourceBone( it->first ); if( sbone != NULL ) { sbone->update( pTime, pPose ); bone->setTransformMatrix( sbone->getLocalTransformMatrix() ); } } } //-------------------------------------------------------------- void ofxFBXSkeleton::lateUpdateWithAnimation() { map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; ofxFBXBone* sbone = getSourceBone( it->first ); if( sbone != NULL ) { sbone->setTransformMatrix( bone->getLocalTransformMatrix() ); // sbone->localTransformMatrix = bone->localTransformMatrix; sbone->setPosition( bone->getPosition() ); sbone->setOrientation( bone->getOrientationQuat() ); sbone->setScale( bone->getScale() ); } } for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; ofxFBXBone* sbone = getSourceBone( it->first ); if( sbone != NULL ) { sbone->updateFbxTransform(); } } } //-------------------------------------------------------------- void ofxFBXSkeleton::updateFromCachedSkeleton( shared_ptr< ofxFBXSkeleton> aSkeleton ) { // updateBoneProperties(); map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; // ofxFBXBone* sbone = getSourceBone( it->first ); // ofxFBXBone* sbone = aSkeleton->getSourceBone( it->first ); ofxFBXBone* obone = aSkeleton->getBone( it->first ); if( obone != NULL ) { // // localTransformMatrix = m44; // // ofQuaternion so; // localTransformMatrix.decompose(position, orientation, scale, so); // // onPositionChanged(); // onOrientationChanged(); // onScaleChanged(); // sbone->update( pTime, NULL ); bone->setTransformMatrix( obone->getLocalTransformMatrix() ); // bone->localTransformMatrix = obone->localTransformMatrix; bone->setPosition( obone->getPosition() ); bone->setOrientation( obone->getOrientationQuat() ); bone->setScale( obone->getScale() ); } else { ofLogWarning() << "updateFromCachedSkeleton: " << it->first << " is null !!" << endl; } } } //-------------------------------------------------------------- void ofxFBXSkeleton::updateBoneProperties() { map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { ofxFBXBone* bone = &it->second; ofxFBXBone* sbone = getSourceBone( it->first ); if( sbone != NULL ) { if( bone->isExternalControlEnabled() ) { sbone->enableExternalControl(); } else { sbone->disableExternalControl(); } if( bone->isAnimationEnabled() ) { sbone->enableAnimation(); } else { sbone->disableAnimation(); } } } } //-------------------------------------------------------------- void ofxFBXSkeleton::draw( float aLen ) { map<string, ofxFBXBone>::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { it->second.draw(aLen); } } //-------------------------------------------------------------- void ofxFBXSkeleton::addBone( string aName, ofxFBXBone* aBone ) { if(aName == "") { ofLogWarning("ofxFBXSkeleton :: addBone : name is empty, not adding bone"); return; } if(bones.find(aName) != bones.end()) { // the bone has a duplicate name, try to make a unique key // aName += ofToString(numBones,0); } vector <string> strs;// = ofSplitString(aName, ":"); ofxFBXBone tbone = *aBone; string newBoneName = aName; if(strs.size() > 1) { newBoneName = strs[1]; } // cout << "adding a bone with name -" << newBoneName << "- parent name -" << getName() <<"-" << endl; sourceBones[ newBoneName ] = aBone; bones[ newBoneName ] = tbone; // cout << "ofxFBXSkeleton :: addBone : name: " << aName << " ptr parent = " << aBone->getParent() << " other: " << tbone.getParent() << endl; numBones++; } //-------------------------------------------------------------- ofxFBXBone* ofxFBXSkeleton::getBone( string aName ) { if(bones.find(aName) != bones.end()) { return &bones[ aName ]; } cout << "did not find the bone with name: " << aName << " | " << ofGetElapsedTimef() << endl; return NULL; } //-------------------------------------------------------------- ofxFBXBone* ofxFBXSkeleton::getSourceBone( string aName ) { if(bones.find(aName) != bones.end()) { return sourceBones[ aName ]; } return NULL; } //-------------------------------------------------------------- void ofxFBXSkeleton::enableExternalControl( string aName ) { // loop through hierarchy to make children also controlled externally ofxFBXBone* bone = getBone( aName ); if(bone == NULL) { ofLogWarning("ofxFBXSkeleton :: enableExternalControl : can not find bone with name ") << aName; return; } bone->enableExternalControl(); enableExternalControlRecursive( getSourceBone(aName) ); } //-------------------------------------------------------------- void ofxFBXSkeleton::enableExternalControlRecursive( ofxFBXBone* aBone ) { if( aBone == NULL ) return; map<string, ofxFBXBone* >::iterator it; for(it = sourceBones.begin(); it != sourceBones.end(); ++it ) { if( it->second->fbxNode->GetParent() == aBone->fbxNode ) { // it->second->enableExternalControl(); getBone( it->first )->enableExternalControl(); enableExternalControlRecursive( it->second ); } } } //-------------------------------------------------------------- void ofxFBXSkeleton::enableAnimation() { map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { it->second.enableAnimation(); } } //-------------------------------------------------------------- void ofxFBXSkeleton::disableAnimation() { map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { it->second.disableAnimation(); } } //-------------------------------------------------------------- int ofxFBXSkeleton::getNumBones() { return (int)bones.size(); } //-------------------------------------------------------------- void ofxFBXSkeleton::reset() { map<string, ofxFBXBone >::iterator it; for(it = bones.begin(); it != bones.end(); ++it ) { it->second.reset(); } } //-------------------------------------------------------------- string ofxFBXSkeleton::toString() { map<string, ofxFBXBone >::iterator it; map< string, bool > printMap; for(it = bones.begin(); it != bones.end(); ++it ) { printMap[ it->first ] = false; } stringstream ss; ss << "Skeleton: " << getName() << " - Number of bones: " << bones.size() << endl; if( bones.size() ) { printOutBoneRecursive(ss, sourceBones.begin()->first, printMap, "" ); } else { ss << "NO BONES" << endl; } return ss.str().c_str(); } //-------------------------------------------------------------- void ofxFBXSkeleton::printOutBoneRecursive( stringstream& aSS, string aBoneName, map< string, bool >& aPrintMap, string aSpacer ) { if( aPrintMap[ aBoneName ] ) return; aPrintMap[ aBoneName ] = true; ofxFBXBone* bone = getSourceBone( aBoneName ); if( bone == NULL ) return; aSS << aSpacer << " bone: " << aBoneName << " parent: " << bone->parentBoneName << endl; aSpacer += "---"; map<string, ofxFBXBone*>::iterator it; for(it = sourceBones.begin(); it != sourceBones.end(); ++it ) { if( it->second->fbxNode->GetParent() == bone->fbxNode ) { printOutBoneRecursive( aSS, it->first, aPrintMap, aSpacer ); } } } <|endoftext|>
<commit_before>#include "MazeFileUtilities.h" #include <fstream> #include <iostream> #include <iterator> #include <sstream> #include <vector> #ifdef _WIN32 #include <windows.h> #elif __linux #include <limits.h> #include <unistd.h> #endif namespace sim { std::string getProjectDirectory(){ // This approach is claimed to be more reliable than argv[0] on windows // and linux. On Windows GetModuleFileName is the directory to the executable // which is located in /mms/src/Debug/. On linux /proc/self/exe is a path to exe. // This aproach does not work for all flavors to Linux, should on the common. // executable on Linux is located at /mms/bin/ std::string path; #ifdef _WIN32 char result[MAX_PATH]; path = std::string(result, GetModuleFileName(NULL, result, MAX_PATH)); path = path.substr(0, path.find_last_of("\\/"));; // Remove the executable name as it is part of path path += "\\..\\..\\"; // Point to /mms/ // Windows uses \ in directory #elif __linux char result[PATH_MAX]; ssize_t count = readlink("/proc/self/exe", result, PATH_MAX); path = std::string(result, (count > 0) ? count : 0); path = path.substr(0, path.find_last_of("\\/"));; // Remove the executable name as it is part of path path += "/../"; // Point to /mms/ #endif return path; } std::string getMazeFileDirPath(){ std::string path; path = getProjectDirectory(); // Append mazeFile directory path from the root of the project path += "src/maze_files/"; return path; } /*int mazeFileWidth(std::string mazeFilePath){ } int mazeFileHeight(std::string mazeFilePath){ } */ bool checkValidMazeFile(std::string mazeFilePath){ // TODO: Ensure that you have unique y values for all x values // TODO: Ensure that the walls line up // TODO: Make a mazeFileValidator - gets height, width, valid, etc // This function validates following: // 1.) There are an equal number of y values for each x value // 2.) All the x and y values are unique // 3.) The walls are valid // Create the file object std::ifstream file(mazeFilePath.c_str()); // Initialize a string variable std::string line(""); if (file.is_open()){ // Vector that counts the number of y values colums for each x value // TODO std::vector<int> counts; counts.push_back(0); int xValue = 0; while (getline(file, line)){ std::istringstream iss(line); std::vector<std::string> tokens; copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter<std::vector<std::string> >(tokens)); // Counting logic // TODO /*if (tokens.at(0) == xValue){ counts.at(xValue) += 1; } else{ xValue = tokens.at(0); counts.push_back(1); }*/ } file.close(); /*int numberOfYValues = counts.at(0); for (int i = 1; i < counts.size(); i += 1){ if (counts.at(i) != numberOfYValues){ return 0; } }*/ } // false indicates invalid file return false; } bool checkValidMazeFileTom(std::string mazeFilePath, int height, int width){ // Create the file object std::ifstream file(mazeFilePath.c_str()); // Error opening file if (!file.is_open()) { return false; } // Initialize a string variable std::string line(""); int expected_x_pos = 0; int expected_y_pos = 0; int current_int = 0; while (std::getline(file, line)) { if (!hasOnlyDigits(line)){ // The line has some non digit characters return false; } for (int i = 0; i < 6; i += 1) { if (line.at(0) == ' '){ //Check that the first character is not a space //This would only occur if two spaces apear in a row return false; } current_int = std::strtol(line.c_str(), nullptr, 10); //Get the next int an integer which is followed by a space if (i == 0 && current_int != expected_x_pos){ // X Pos on line does not match the expected X Position return false; } if (i == 1){ // Y Pos Handliing if (current_int != expected_y_pos){ // Y Pos on line does not match the expected Y Position return false; } expected_y_pos += 1; // Add one to the expected Y_position if (expected_y_pos == height) { // Wrap Around expected_y_pos = 0; expected_x_pos += 1; // X-Pos will increase } } if (i > 1 && !(current_int == 0 || current_int == 1)) { // Wall Values - check if 1 or 0 return false; } std::size_t found = line.find_first_of(" "); if (found != std::string::npos) { // extra space exists in the string line = line.substr(line.find_first_of(" ") + 1, line.length()); if (i == 5) { return false; // return false if more spaces after last digit remain } } else if (i != 5) { return false; // If no more spaces before the last digit that means the line // does not have enough digits } } } if (expected_x_pos != width && expected_y_pos != 0) { return false; // Not all lines present in the last group } // TODO: Maze validation - has a path to the center, no wall following robot, etc. // TODO: Make sure the neighboring tiles have corresponding walls (if a tile has // a wall to the right, the tile to its right should have a wall to the left, etc.) return true; //should be fine } bool hasOnlyDigits(const std::string &str) { return str.find_first_not_of("0123456789 ") == std::string::npos; } } // namespace sim <commit_msg>Maze valid fix<commit_after>#include "MazeFileUtilities.h" #include <fstream> #include <iostream> #include <iterator> #include <sstream> #include <vector> #ifdef _WIN32 #include <windows.h> #elif __linux #include <limits.h> #include <unistd.h> #endif namespace sim { std::string getProjectDirectory(){ // This approach is claimed to be more reliable than argv[0] on windows // and linux. On Windows GetModuleFileName is the directory to the executable // which is located in /mms/src/Debug/. On linux /proc/self/exe is a path to exe. // This aproach does not work for all flavors to Linux, should on the common. // executable on Linux is located at /mms/bin/ std::string path; #ifdef _WIN32 char result[MAX_PATH]; path = std::string(result, GetModuleFileName(NULL, result, MAX_PATH)); path = path.substr(0, path.find_last_of("\\/"));; // Remove the executable name as it is part of path path += "\\..\\..\\"; // Point to /mms/ // Windows uses \ in directory #elif __linux char result[PATH_MAX]; ssize_t count = readlink("/proc/self/exe", result, PATH_MAX); path = std::string(result, (count > 0) ? count : 0); path = path.substr(0, path.find_last_of("\\/"));; // Remove the executable name as it is part of path path += "/../"; // Point to /mms/ #endif return path; } std::string getMazeFileDirPath(){ std::string path; path = getProjectDirectory(); // Append mazeFile directory path from the root of the project path += "src/maze_files/"; return path; } /*int mazeFileWidth(std::string mazeFilePath){ } int mazeFileHeight(std::string mazeFilePath){ } */ bool checkValidMazeFile(std::string mazeFilePath){ // TODO: Ensure that you have unique y values for all x values // TODO: Ensure that the walls line up // TODO: Make a mazeFileValidator - gets height, width, valid, etc // This function validates following: // 1.) There are an equal number of y values for each x value // 2.) All the x and y values are unique // 3.) The walls are valid // Create the file object std::ifstream file(mazeFilePath.c_str()); // Initialize a string variable std::string line(""); if (file.is_open()){ // Vector that counts the number of y values colums for each x value // TODO std::vector<int> counts; counts.push_back(0); int xValue = 0; while (getline(file, line)){ std::istringstream iss(line); std::vector<std::string> tokens; copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter<std::vector<std::string> >(tokens)); // Counting logic // TODO /*if (tokens.at(0) == xValue){ counts.at(xValue) += 1; } else{ xValue = tokens.at(0); counts.push_back(1); }*/ } file.close(); /*int numberOfYValues = counts.at(0); for (int i = 1; i < counts.size(); i += 1){ if (counts.at(i) != numberOfYValues){ return 0; } }*/ } // false indicates invalid file return false; } bool checkValidMazeFileTom(std::string mazeFilePath, int height, int width){ // Create the file object std::ifstream file(mazeFilePath.c_str()); // Error opening file if (!file.is_open()) { return false; } // Initialize a string variable std::string line(""); int expected_x_pos = 0; int expected_y_pos = -1; int current_int = 0; while (std::getline(file, line)) { if (!hasOnlyDigits(line)){ // The line has some non digit characters return false; } expected_y_pos += 1; // Add one to the expected Y_position if (expected_y_pos == height) { // Wrap Around expected_y_pos = 0; expected_x_pos += 1; // X-Pos will increase } if (expected_x_pos == width) { return false; // Too many lines, RUN } for (int i = 0; i < 6; i += 1) { if (line.at(0) == ' '){ //Check that the first character is not a space //This would only occur if two spaces apear in a row return false; } current_int = std::strtol(line.c_str(), nullptr, 10); //Get the next int an integer which is followed by a space if (i == 0 && current_int != expected_x_pos){ // X Pos on line does not match the expected X Position return false; } if (i == 1){ // Y Pos Handliing if (current_int != expected_y_pos){ // Y Pos on line does not match the expected Y Position return false; } } if (i > 1 && !(current_int == 0 || current_int == 1)) { // Wall Values - check if 1 or 0 return false; } std::size_t found = line.find_first_of(" "); if (found != std::string::npos) { // extra space exists in the string line = line.substr(line.find_first_of(" ") + 1, line.length()); if (i == 5) { return false; // return false if more spaces after last digit remain } } else if (i != 5) { return false; // If no more spaces before the last digit that means the line // does not have enough digits } } } if (expected_x_pos != width - 1 && expected_y_pos != 0) { return false; // Not all lines present in the last group } // TODO: Maze validation - has a path to the center, no wall following robot, etc. // TODO: Make sure the neighboring tiles have corresponding walls (if a tile has // a wall to the right, the tile to its right should have a wall to the left, etc.) return true; //should be fine } bool hasOnlyDigits(const std::string &str) { return str.find_first_not_of("0123456789 ") == std::string::npos; } } // namespace sim <|endoftext|>
<commit_before>#include <cmath> #include <array> #include <chrono> #include <sstream> #include <iostream> #include <iomanip> #include <algorithm> #include <sys/stat.h> #include "simulation.h" #include "codes/codes.h" namespace detail { inline bool file_exists(const std::string &fname) { struct stat buf; return (stat(fname.c_str(), &buf) != -1); } } static std::array<double, 131> rates{ { 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.20, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.30, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.40, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.50, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.60, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69, 0.70, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.800, 0.807, 0.817, 0.827, 0.837, 0.846, 0.855, 0.864, 0.872, 0.880, 0.887, 0.894, 0.900, 0.907, 0.913, 0.918, 0.924, 0.929, 0.934, 0.938, 0.943, 0.947, 0.951, 0.954, 0.958, 0.961, 0.964, 0.967, 0.970, 0.972, 0.974, 0.976, 0.978, 0.980, 0.982, 0.983, 0.984, 0.985, 0.986, 0.987, 0.988, 0.989, 0.990, 0.991, 0.992, 0.993, 0.994, 0.995, 0.996, 0.997, 0.998, 0.999 } }; static std::array<double, 131> limits = { { -1.548, -1.531, -1.500, -1.470, -1.440, -1.409, -1.378, -1.347, -1.316, -1.285, -1.254, -1.222, -1.190, -1.158, -1.126, -1.094, -1.061, -1.028, -0.995, -0.963, -0.928, -0.896, -0.861, -0.827, -0.793, -0.757, -0.724, -0.687, -0.651, -0.616, -0.579, -0.544, -0.507, -0.469, -0.432, -0.394, -0.355, -0.314, -0.276, -0.236, -0.198, -0.156, -0.118, -0.074, -0.032, 0.010, 0.055, 0.097, 0.144, 0.188, 0.233, 0.279, 0.326, 0.374, 0.424, 0.474, 0.526, 0.574, 0.628, 0.682, 0.734, 0.791, 0.844, 0.904, 0.960, 1.021, 1.084, 1.143, 1.208, 1.275, 1.343, 1.412, 1.483, 1.554, 1.628, 1.708, 1.784, 1.867, 1.952, 2.045, 2.108, 2.204, 2.302, 2.402, 2.503, 2.600, 2.712, 2.812, 2.913, 3.009, 3.114, 3.205, 3.312, 3.414, 3.500, 3.612, 3.709, 3.815, 3.906, 4.014, 4.115, 4.218, 4.304, 4.425, 4.521, 4.618, 4.725, 4.841, 4.922, 5.004, 5.104, 5.196, 5.307, 5.418, 5.484, 5.549, 5.615, 5.681, 5.756, 5.842, 5.927, 6.023, 6.119, 6.234, 6.360, 6.495, 6.651, 6.837, 7.072, 7.378, 7.864 } }; static constexpr double ebno(const double rate) { if (rate <= 0.800) { const size_t index = static_cast<size_t>(rate * 100); return limits.at(index); } else if (rate >= 0.999) { return limits.back(); } else { const size_t offset = 80; const size_t index = static_cast<size_t>(std::distance( std::cbegin(rates), std::find_if(std::cbegin(rates) + offset, std::cend(rates) - 1, [=](const double r) { return r >= rate; }))); return limits.at(index); } } static std::ofstream open_file(const std::string &fname) { if (detail::file_exists(fname)) { std::ostringstream os; os << "File " << fname << " already exists."; throw std::runtime_error(os.str()); } std::ofstream log_file(fname.c_str(), std::ofstream::out); return log_file; } double awgn_simulation::sigma(const double eb_no) const { return 1.0f / sqrt((2 * decoder.rate() * pow(10, eb_no / 10.0))); } awgn_simulation::awgn_simulation(const class decoder &decoder_, const double step_, const uint64_t seed_) : decoder(decoder_), step(step_), seed(seed_) {} void awgn_simulation::operator()() { const size_t wer_width = std::numeric_limits<double>::digits10; const size_t ebno_width = 6; std::ofstream log_file(open_file(decoder.to_string() + ".log")); std::vector<float> b(decoder.n()); log_file << std::setw(ebno_width + 1) << "ebno" << " "; log_file << std::setw(wer_width + 6) << "wer" << std::endl; const size_t factor = static_cast<size_t>(1.0 / step); const size_t tmp = static_cast<size_t>(ebno(decoder.rate()) / step); const double start = (tmp + (1.0 / step)) * step; const double max = std::max(8.0, start) + step / 2; /* TODO round ebno() up to next step */ for (double eb_no = start; eb_no < max; eb_no += step) { std::normal_distribution<float> distribution( 1.0, static_cast<float>(sigma(eb_no))); auto noise = std::bind(std::ref(distribution), std::ref(generator)); size_t word_errors = 0; size_t samples = 10000; std::cout << std::this_thread::get_id() << " " << decoder.to_string() << ": E_b/N_0 = " << eb_no << " with " << samples << " โ€ฆ "; std::cout.flush(); auto start_time = std::chrono::high_resolution_clock::now(); for (size_t i = 0; i < samples; i++) { std::generate(std::begin(b), std::end(b), noise); try { auto result = decoder.correct(b); if (std::any_of(std::cbegin(result), std::cend(result), [](const auto &bit) { return bool(bit); })) { word_errors++; } } catch (const decoding_failure &) { word_errors++; } } auto end_time = std::chrono::high_resolution_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>( end_time - start_time).count(); std::cout << seconds << " s" << std::endl; log_file << std::setw(ebno_width + 1) << std::setprecision(ebno_width) << std::defaultfloat << eb_no << " "; log_file << std::setw(wer_width + 1) << std::setprecision(wer_width) << std::scientific << (double)word_errors / samples << std::endl; } } bitflip_simulation::bitflip_simulation(const class decoder &decoder, const size_t errors) : decoder(decoder), errors(errors) {} void bitflip_simulation::operator()() const { const size_t wer_width = std::numeric_limits<double>::digits10; const size_t ebno_width = 6; std::ofstream log_file(open_file(decoder.to_string() + ".log")); std::vector<float> b(decoder.n()); log_file << std::setw(ebno_width + 1) << "errors" << " "; log_file << std::setw(wer_width + 6) << "wer" << std::endl; const size_t length = decoder.n(); for (size_t error = 0; error <= errors; error++) { size_t patterns = 0; size_t word_errors = 0; std::vector<int> b; std::fill_n(std::back_inserter(b), length - error, 0); std::fill_n(std::back_inserter(b), error, 1); std::cout << std::this_thread::get_id() << " " << decoder.to_string() << ": errors = " << error << " โ€ฆ "; std::cout.flush(); auto start = std::chrono::high_resolution_clock::now(); do { std::vector<float> x; x.reserve(length); std::transform(std::cbegin(b), std::cend(b), std::back_inserter(x), [](const auto &bit) { return -2 * bit + 1; }); patterns++; try { auto result = decoder.correct(x); if (std::any_of(std::cbegin(result), std::cend(result), [](const auto &bit) { return bool(bit); })) { word_errors++; } } catch (const decoding_failure &) { word_errors++; } } while (std::next_permutation(std::begin(b), std::end(b))); auto end = std::chrono::high_resolution_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(end - start).count(); std::cout << seconds << " s " << word_errors << " " << patterns << std::endl; log_file << std::setw(ebno_width + 1) << std::setprecision(ebno_width) << std::defaultfloat << error << " "; log_file << std::setw(wer_width + 1) << std::setprecision(wer_width) << std::scientific << (double)word_errors / patterns << std::endl; } } std::atomic_bool thread_pool::running{ true }; std::mutex thread_pool::lock; std::condition_variable thread_pool::cv; std::list<std::function<void(void)> > thread_pool::queue; thread_pool::thread_pool() { for (unsigned i = 0; i < std::thread::hardware_concurrency(); i++) { pool.emplace_back(std::bind(&thread_pool::thread_function, this)); } } thread_pool::~thread_pool() { running = false; cv.notify_all(); for (auto &&t : pool) t.join(); } void thread_pool::thread_function() const { for (;;) { bool have_work = false; std::function<void(void)> work; { std::unique_lock<std::mutex> m(lock); /* * empty running wait * 0 0 0 * 0 1 0 * 1 0 0 * 1 1 1 */ cv.wait(m, [&]() { return !(queue.empty() && running); }); if (!queue.empty()) { work = queue.front(); queue.pop_front(); have_work = true; } } if (have_work) { try { work(); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } } else if (!running) { return; } } } <commit_msg>Replace old-style cast with static_cast<commit_after>#include <cmath> #include <array> #include <chrono> #include <sstream> #include <iostream> #include <iomanip> #include <algorithm> #include <sys/stat.h> #include "simulation.h" #include "codes/codes.h" namespace detail { inline bool file_exists(const std::string &fname) { struct stat buf; return (stat(fname.c_str(), &buf) != -1); } } static std::array<double, 131> rates{ { 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.20, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.30, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.40, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.50, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.60, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69, 0.70, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.800, 0.807, 0.817, 0.827, 0.837, 0.846, 0.855, 0.864, 0.872, 0.880, 0.887, 0.894, 0.900, 0.907, 0.913, 0.918, 0.924, 0.929, 0.934, 0.938, 0.943, 0.947, 0.951, 0.954, 0.958, 0.961, 0.964, 0.967, 0.970, 0.972, 0.974, 0.976, 0.978, 0.980, 0.982, 0.983, 0.984, 0.985, 0.986, 0.987, 0.988, 0.989, 0.990, 0.991, 0.992, 0.993, 0.994, 0.995, 0.996, 0.997, 0.998, 0.999 } }; static std::array<double, 131> limits = { { -1.548, -1.531, -1.500, -1.470, -1.440, -1.409, -1.378, -1.347, -1.316, -1.285, -1.254, -1.222, -1.190, -1.158, -1.126, -1.094, -1.061, -1.028, -0.995, -0.963, -0.928, -0.896, -0.861, -0.827, -0.793, -0.757, -0.724, -0.687, -0.651, -0.616, -0.579, -0.544, -0.507, -0.469, -0.432, -0.394, -0.355, -0.314, -0.276, -0.236, -0.198, -0.156, -0.118, -0.074, -0.032, 0.010, 0.055, 0.097, 0.144, 0.188, 0.233, 0.279, 0.326, 0.374, 0.424, 0.474, 0.526, 0.574, 0.628, 0.682, 0.734, 0.791, 0.844, 0.904, 0.960, 1.021, 1.084, 1.143, 1.208, 1.275, 1.343, 1.412, 1.483, 1.554, 1.628, 1.708, 1.784, 1.867, 1.952, 2.045, 2.108, 2.204, 2.302, 2.402, 2.503, 2.600, 2.712, 2.812, 2.913, 3.009, 3.114, 3.205, 3.312, 3.414, 3.500, 3.612, 3.709, 3.815, 3.906, 4.014, 4.115, 4.218, 4.304, 4.425, 4.521, 4.618, 4.725, 4.841, 4.922, 5.004, 5.104, 5.196, 5.307, 5.418, 5.484, 5.549, 5.615, 5.681, 5.756, 5.842, 5.927, 6.023, 6.119, 6.234, 6.360, 6.495, 6.651, 6.837, 7.072, 7.378, 7.864 } }; static constexpr double ebno(const double rate) { if (rate <= 0.800) { const size_t index = static_cast<size_t>(rate * 100); return limits.at(index); } else if (rate >= 0.999) { return limits.back(); } else { const size_t offset = 80; const size_t index = static_cast<size_t>(std::distance( std::cbegin(rates), std::find_if(std::cbegin(rates) + offset, std::cend(rates) - 1, [=](const double r) { return r >= rate; }))); return limits.at(index); } } static std::ofstream open_file(const std::string &fname) { if (detail::file_exists(fname)) { std::ostringstream os; os << "File " << fname << " already exists."; throw std::runtime_error(os.str()); } std::ofstream log_file(fname.c_str(), std::ofstream::out); return log_file; } double awgn_simulation::sigma(const double eb_no) const { return 1.0f / sqrt((2 * decoder.rate() * pow(10, eb_no / 10.0))); } awgn_simulation::awgn_simulation(const class decoder &decoder_, const double step_, const uint64_t seed_) : decoder(decoder_), step(step_), seed(seed_) {} void awgn_simulation::operator()() { const size_t wer_width = std::numeric_limits<double>::digits10; const size_t ebno_width = 6; std::ofstream log_file(open_file(decoder.to_string() + ".log")); std::vector<float> b(decoder.n()); log_file << std::setw(ebno_width + 1) << "ebno" << " "; log_file << std::setw(wer_width + 6) << "wer" << std::endl; const size_t factor = static_cast<size_t>(1.0 / step); const size_t tmp = static_cast<size_t>(ebno(decoder.rate()) / step); const double start = (tmp + (1.0 / step)) * step; const double max = std::max(8.0, start) + step / 2; /* TODO round ebno() up to next step */ for (double eb_no = start; eb_no < max; eb_no += step) { std::normal_distribution<float> distribution( 1.0, static_cast<float>(sigma(eb_no))); auto noise = std::bind(std::ref(distribution), std::ref(generator)); size_t word_errors = 0; size_t samples = 10000; std::cout << std::this_thread::get_id() << " " << decoder.to_string() << ": E_b/N_0 = " << eb_no << " with " << samples << " โ€ฆ "; std::cout.flush(); auto start_time = std::chrono::high_resolution_clock::now(); for (size_t i = 0; i < samples; i++) { std::generate(std::begin(b), std::end(b), noise); try { auto result = decoder.correct(b); if (std::any_of(std::cbegin(result), std::cend(result), [](const auto &bit) { return bool(bit); })) { word_errors++; } } catch (const decoding_failure &) { word_errors++; } } auto end_time = std::chrono::high_resolution_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>( end_time - start_time).count(); std::cout << seconds << " s" << std::endl; log_file << std::setw(ebno_width + 1) << std::setprecision(ebno_width) << std::defaultfloat << eb_no << " "; log_file << std::setw(wer_width + 1) << std::setprecision(wer_width) << std::scientific << static_cast<double>(word_errors) / samples << std::endl; } } bitflip_simulation::bitflip_simulation(const class decoder &decoder, const size_t errors) : decoder(decoder), errors(errors) {} void bitflip_simulation::operator()() const { const size_t wer_width = std::numeric_limits<double>::digits10; const size_t ebno_width = 6; std::ofstream log_file(open_file(decoder.to_string() + ".log")); std::vector<float> b(decoder.n()); log_file << std::setw(ebno_width + 1) << "errors" << " "; log_file << std::setw(wer_width + 6) << "wer" << std::endl; const size_t length = decoder.n(); for (size_t error = 0; error <= errors; error++) { size_t patterns = 0; size_t word_errors = 0; std::vector<int> b; std::fill_n(std::back_inserter(b), length - error, 0); std::fill_n(std::back_inserter(b), error, 1); std::cout << std::this_thread::get_id() << " " << decoder.to_string() << ": errors = " << error << " โ€ฆ "; std::cout.flush(); auto start = std::chrono::high_resolution_clock::now(); do { std::vector<float> x; x.reserve(length); std::transform(std::cbegin(b), std::cend(b), std::back_inserter(x), [](const auto &bit) { return -2 * bit + 1; }); patterns++; try { auto result = decoder.correct(x); if (std::any_of(std::cbegin(result), std::cend(result), [](const auto &bit) { return bool(bit); })) { word_errors++; } } catch (const decoding_failure &) { word_errors++; } } while (std::next_permutation(std::begin(b), std::end(b))); auto end = std::chrono::high_resolution_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(end - start).count(); std::cout << seconds << " s " << word_errors << " " << patterns << std::endl; log_file << std::setw(ebno_width + 1) << std::setprecision(ebno_width) << std::defaultfloat << error << " "; log_file << std::setw(wer_width + 1) << std::setprecision(wer_width) << std::scientific << (double)word_errors / patterns << std::endl; } } std::atomic_bool thread_pool::running{ true }; std::mutex thread_pool::lock; std::condition_variable thread_pool::cv; std::list<std::function<void(void)> > thread_pool::queue; thread_pool::thread_pool() { for (unsigned i = 0; i < std::thread::hardware_concurrency(); i++) { pool.emplace_back(std::bind(&thread_pool::thread_function, this)); } } thread_pool::~thread_pool() { running = false; cv.notify_all(); for (auto &&t : pool) t.join(); } void thread_pool::thread_function() const { for (;;) { bool have_work = false; std::function<void(void)> work; { std::unique_lock<std::mutex> m(lock); /* * empty running wait * 0 0 0 * 0 1 0 * 1 0 0 * 1 1 1 */ cv.wait(m, [&]() { return !(queue.empty() && running); }); if (!queue.empty()) { work = queue.front(); queue.pop_front(); have_work = true; } } if (have_work) { try { work(); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } } else if (!running) { return; } } } <|endoftext|>
<commit_before>// Floating Temple // Copyright 2015 Derek S. Snyder // // 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 "peer/versioned_object_content.h" #include <map> #include <memory> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "base/escape.h" #include "base/linked_ptr.h" #include "base/logging.h" #include "base/mutex.h" #include "base/mutex_lock.h" #include "base/string_printf.h" #include "peer/canonical_peer.h" #include "peer/committed_event.h" #include "peer/live_object.h" #include "peer/max_version_map.h" #include "peer/peer_exclusion_map.h" #include "peer/peer_thread.h" #include "peer/proto/transaction_id.pb.h" #include "peer/sequence_point_impl.h" #include "peer/shared_object_transaction.h" #include "peer/shared_object_transaction_info.h" #include "peer/transaction_id_util.h" #include "peer/transaction_store_internal_interface.h" using std::map; using std::pair; using std::shared_ptr; using std::string; using std::unordered_map; using std::unordered_set; using std::vector; namespace floating_temple { namespace peer { namespace { vector<pair<const CanonicalPeer*, TransactionId>>::const_iterator FindTransactionIdInVector( const vector<pair<const CanonicalPeer*, TransactionId>>& transaction_pairs, const TransactionId& transaction_id) { const vector<pair<const CanonicalPeer*, TransactionId>>::const_iterator end_it = transaction_pairs.end(); vector<pair<const CanonicalPeer*, TransactionId>>::const_iterator it = transaction_pairs.begin(); while (it != end_it && CompareTransactionIds(it->second, transaction_id) != 0) { ++it; } return it; } } // namespace VersionedObjectContent::VersionedObjectContent( TransactionStoreInternalInterface* transaction_store, SharedObject* shared_object) : transaction_store_(CHECK_NOTNULL(transaction_store)), shared_object_(CHECK_NOTNULL(shared_object)) { } VersionedObjectContent::~VersionedObjectContent() { } shared_ptr<const LiveObject> VersionedObjectContent::GetWorkingVersion( const MaxVersionMap& transaction_store_version_map, const SequencePointImpl& sequence_point, unordered_map<SharedObject*, PeerObjectImpl*>* new_peer_objects, vector<pair<const CanonicalPeer*, TransactionId>>* transactions_to_reject) { MutexLock lock(&committed_versions_mu_); MaxVersionMap effective_version; ComputeEffectiveVersion_Locked(transaction_store_version_map, &effective_version); if (!VersionMapIsLessThanOrEqual(sequence_point.version_map(), effective_version)) { VLOG(1) << "sequence_point.version_map() == " << sequence_point.version_map().Dump(); VLOG(1) << "effective_version == " << effective_version.Dump(); return shared_ptr<const LiveObject>(nullptr); } if (CanUseCachedLiveObject_Locked(sequence_point)) { CHECK(cached_live_object_.get() != nullptr); return cached_live_object_; } for (;;) { PeerThread peer_thread; peer_thread.Start(transaction_store_, shared_object_, shared_ptr<LiveObject>(nullptr), new_peer_objects); const bool success = ApplyTransactionsToWorkingVersion_Locked( &peer_thread, sequence_point, transactions_to_reject); peer_thread.Stop(); if (success) { return peer_thread.live_object(); } } return shared_ptr<const LiveObject>(nullptr); } void VersionedObjectContent::GetTransactions( const MaxVersionMap& transaction_store_version_map, map<TransactionId, linked_ptr<SharedObjectTransactionInfo>>* transactions, MaxVersionMap* effective_version) const { CHECK(transactions != nullptr); MutexLock lock(&committed_versions_mu_); for (const auto& transaction_pair : committed_versions_) { const TransactionId& transaction_id = transaction_pair.first; const SharedObjectTransaction& transaction = *transaction_pair.second; SharedObjectTransactionInfo* const transaction_info = new SharedObjectTransactionInfo(); const vector<linked_ptr<CommittedEvent>>& src_events = transaction.events(); vector<linked_ptr<CommittedEvent>>* const dest_events = &transaction_info->events; const vector<linked_ptr<CommittedEvent>>::size_type event_count = src_events.size(); dest_events->resize(event_count); for (vector<linked_ptr<CommittedEvent>>::size_type i = 0; i < event_count; ++i) { (*dest_events)[i].reset(src_events[i]->Clone()); } transaction_info->origin_peer = transaction.origin_peer(); CHECK(transactions->emplace(transaction_id, make_linked_ptr(transaction_info)).second); } ComputeEffectiveVersion_Locked(transaction_store_version_map, effective_version); } void VersionedObjectContent::StoreTransactions( const CanonicalPeer* origin_peer, map<TransactionId, linked_ptr<SharedObjectTransactionInfo>>* transactions, const MaxVersionMap& version_map) { CHECK(origin_peer != nullptr); CHECK(transactions != nullptr); MutexLock lock(&committed_versions_mu_); for (const auto& transaction_pair : *transactions) { const TransactionId& transaction_id = transaction_pair.first; SharedObjectTransactionInfo* const transaction_info = transaction_pair.second.get(); CHECK(IsValidTransactionId(transaction_id)); CHECK(transaction_info != nullptr); vector<linked_ptr<CommittedEvent>>* const events = &transaction_info->events; // TODO(dss): Rename this local variable to distinguish it from the // parameter 'origin_peer'. const CanonicalPeer* const origin_peer = transaction_info->origin_peer; CHECK(origin_peer != nullptr); linked_ptr<SharedObjectTransaction>& transaction = committed_versions_[transaction_id]; if (transaction.get() == nullptr) { transaction.reset(new SharedObjectTransaction(events, origin_peer)); } // TODO(dss): [BUG] The following statement should use the parameter named // 'origin_peer', not the local variable with the same name. version_map_.AddPeerTransactionId(origin_peer, transaction_id); } MaxVersionMap new_version_map; GetVersionMapUnion(version_map_, version_map, &new_version_map); version_map_.Swap(&new_version_map); up_to_date_peers_.insert(origin_peer); } void VersionedObjectContent::InsertTransaction( const CanonicalPeer* origin_peer, const TransactionId& transaction_id, vector<linked_ptr<CommittedEvent>>* events) { CHECK(origin_peer != nullptr); CHECK(IsValidTransactionId(transaction_id)); CHECK(events != nullptr); MutexLock lock(&committed_versions_mu_); linked_ptr<SharedObjectTransaction>& transaction = committed_versions_[transaction_id]; if (transaction.get() == nullptr) { transaction.reset(new SharedObjectTransaction(events, origin_peer)); } version_map_.AddPeerTransactionId(origin_peer, transaction_id); up_to_date_peers_.insert(origin_peer); } void VersionedObjectContent::SetCachedLiveObject( const shared_ptr<const LiveObject>& cached_live_object, const SequencePointImpl& cached_sequence_point) { CHECK(cached_live_object.get() != nullptr); MutexLock lock(&committed_versions_mu_); cached_live_object_ = cached_live_object; cached_sequence_point_.CopyFrom(cached_sequence_point); } string VersionedObjectContent::Dump() const { MutexLock lock(&committed_versions_mu_); string committed_versions_string; if (committed_versions_.empty()) { committed_versions_string = "{}"; } else { committed_versions_string = "{"; for (map<TransactionId, linked_ptr<SharedObjectTransaction>>::const_iterator it = committed_versions_.begin(); it != committed_versions_.end(); ++it) { if (it != committed_versions_.begin()) { committed_versions_string += ","; } StringAppendF(&committed_versions_string, " \"%s\": %s", TransactionIdToString(it->first).c_str(), it->second->Dump().c_str()); } committed_versions_string += " }"; } string up_to_date_peers_string; if (up_to_date_peers_.empty()) { up_to_date_peers_string = "[]"; } else { up_to_date_peers_string = "["; for (unordered_set<const CanonicalPeer*>::const_iterator it = up_to_date_peers_.begin(); it != up_to_date_peers_.end(); ++it) { if (it != up_to_date_peers_.begin()) { up_to_date_peers_string += ","; } StringAppendF(&up_to_date_peers_string, " \"%s\"", CEscape((*it)->peer_id()).c_str()); } up_to_date_peers_string += " ]"; } return StringPrintf( "{ \"committed_versions\": %s, \"version_map\": %s, " "\"up_to_date_peers\": %s, \"cached_live_object\": %s, " "\"cached_sequence_point\": %s }", committed_versions_string.c_str(), version_map_.Dump().c_str(), up_to_date_peers_string.c_str(), cached_live_object_->Dump().c_str(), cached_sequence_point_.Dump().c_str()); } bool VersionedObjectContent::ApplyTransactionsToWorkingVersion_Locked( PeerThread* peer_thread, const SequencePointImpl& sequence_point, vector<pair<const CanonicalPeer*, TransactionId>>* transactions_to_reject) { CHECK(peer_thread != nullptr); CHECK(transactions_to_reject != nullptr); for (const auto& transaction_pair : committed_versions_) { const TransactionId& transaction_id = transaction_pair.first; const SharedObjectTransaction& transaction = *transaction_pair.second; const vector<linked_ptr<CommittedEvent>>& events = transaction.events(); if (!events.empty()) { const CanonicalPeer* const origin_peer = transaction.origin_peer(); if (sequence_point.HasPeerTransactionId(origin_peer, transaction_id) && FindTransactionIdInVector(*transactions_to_reject, transaction_id) == transactions_to_reject->end()) { for (const linked_ptr<CommittedEvent>& event : events) { peer_thread->QueueEvent(event.get()); } peer_thread->FlushEvents(); if (peer_thread->conflict_detected()) { transactions_to_reject->emplace_back(origin_peer, transaction_id); return false; } } } } return true; } void VersionedObjectContent::ComputeEffectiveVersion_Locked( const MaxVersionMap& transaction_store_version_map, MaxVersionMap* effective_version) const { CHECK(effective_version != nullptr); const unordered_map<const CanonicalPeer*, TransactionId>& version_map_peer_transaction_ids = version_map_.peer_transaction_ids(); for (const auto& version_map_pair : version_map_peer_transaction_ids) { effective_version->AddPeerTransactionId(version_map_pair.first, version_map_pair.second); } const unordered_map<const CanonicalPeer*, TransactionId>& transaction_store_peer_transaction_ids = transaction_store_version_map.peer_transaction_ids(); for (const CanonicalPeer* const origin_peer : up_to_date_peers_) { const unordered_map<const CanonicalPeer*, TransactionId>::const_iterator it2 = transaction_store_peer_transaction_ids.find(origin_peer); if (it2 != transaction_store_peer_transaction_ids.end()) { effective_version->AddPeerTransactionId(origin_peer, it2->second); } } } bool VersionedObjectContent::CanUseCachedLiveObject_Locked( const SequencePointImpl& requested_sequence_point) const { if (cached_live_object_.get() == nullptr) { return false; } const MaxVersionMap& requested_version_map = requested_sequence_point.version_map(); const MaxVersionMap& cached_version_map = cached_sequence_point_.version_map(); if (!VersionMapIsLessThanOrEqual(cached_version_map, requested_version_map)) { return false; } const unordered_map<const CanonicalPeer*, TransactionId>& requested_peer_transactions_ids = requested_version_map.peer_transaction_ids(); const unordered_map<const CanonicalPeer*, TransactionId>& cached_peer_transactions_ids = cached_version_map.peer_transaction_ids(); for (const auto& requested_peer_pair : requested_peer_transactions_ids) { const CanonicalPeer* const origin_peer = requested_peer_pair.first; const TransactionId& requested_transaction_id = requested_peer_pair.second; const unordered_map<const CanonicalPeer*, TransactionId>::const_iterator cached_peer_it = cached_peer_transactions_ids.find(origin_peer); TransactionId cached_transaction_id; if (cached_peer_it == cached_peer_transactions_ids.end()) { GetMinTransactionId(&cached_transaction_id); } else { cached_transaction_id.CopyFrom(cached_peer_it->second); } const map<TransactionId, linked_ptr<SharedObjectTransaction>>:: const_iterator start_it = committed_versions_.upper_bound( cached_transaction_id); const map<TransactionId, linked_ptr<SharedObjectTransaction>>:: const_iterator end_it = committed_versions_.upper_bound( requested_transaction_id); for (map<TransactionId, linked_ptr<SharedObjectTransaction>>::const_iterator transaction_it = start_it; transaction_it != end_it; ++transaction_it) { const SharedObjectTransaction& shared_object_transaction = *transaction_it->second; if (shared_object_transaction.origin_peer() == origin_peer) { const vector<linked_ptr<CommittedEvent>>& events = shared_object_transaction.events(); for (const linked_ptr<CommittedEvent>& event : events) { const CommittedEvent::Type event_type = event->type(); if (event_type != CommittedEvent::METHOD_CALL && event_type != CommittedEvent::SUB_METHOD_RETURN) { return false; } } } } } if (!PeerExclusionMapsAreEqual(requested_sequence_point.peer_exclusion_map(), cached_sequence_point_.peer_exclusion_map())) { return false; } if (requested_sequence_point.rejected_peers() != cached_sequence_point_.rejected_peers()) { return false; } return true; } } // namespace peer } // namespace floating_temple <commit_msg>Fix a bug in VersionedObjectContent::Dump() that caused a segfault if cached_live_object_ was null.<commit_after>// Floating Temple // Copyright 2015 Derek S. Snyder // // 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 "peer/versioned_object_content.h" #include <map> #include <memory> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "base/escape.h" #include "base/linked_ptr.h" #include "base/logging.h" #include "base/mutex.h" #include "base/mutex_lock.h" #include "base/string_printf.h" #include "peer/canonical_peer.h" #include "peer/committed_event.h" #include "peer/live_object.h" #include "peer/max_version_map.h" #include "peer/peer_exclusion_map.h" #include "peer/peer_thread.h" #include "peer/proto/transaction_id.pb.h" #include "peer/sequence_point_impl.h" #include "peer/shared_object_transaction.h" #include "peer/shared_object_transaction_info.h" #include "peer/transaction_id_util.h" #include "peer/transaction_store_internal_interface.h" using std::map; using std::pair; using std::shared_ptr; using std::string; using std::unordered_map; using std::unordered_set; using std::vector; namespace floating_temple { namespace peer { namespace { vector<pair<const CanonicalPeer*, TransactionId>>::const_iterator FindTransactionIdInVector( const vector<pair<const CanonicalPeer*, TransactionId>>& transaction_pairs, const TransactionId& transaction_id) { const vector<pair<const CanonicalPeer*, TransactionId>>::const_iterator end_it = transaction_pairs.end(); vector<pair<const CanonicalPeer*, TransactionId>>::const_iterator it = transaction_pairs.begin(); while (it != end_it && CompareTransactionIds(it->second, transaction_id) != 0) { ++it; } return it; } } // namespace VersionedObjectContent::VersionedObjectContent( TransactionStoreInternalInterface* transaction_store, SharedObject* shared_object) : transaction_store_(CHECK_NOTNULL(transaction_store)), shared_object_(CHECK_NOTNULL(shared_object)) { } VersionedObjectContent::~VersionedObjectContent() { } shared_ptr<const LiveObject> VersionedObjectContent::GetWorkingVersion( const MaxVersionMap& transaction_store_version_map, const SequencePointImpl& sequence_point, unordered_map<SharedObject*, PeerObjectImpl*>* new_peer_objects, vector<pair<const CanonicalPeer*, TransactionId>>* transactions_to_reject) { MutexLock lock(&committed_versions_mu_); MaxVersionMap effective_version; ComputeEffectiveVersion_Locked(transaction_store_version_map, &effective_version); if (!VersionMapIsLessThanOrEqual(sequence_point.version_map(), effective_version)) { VLOG(1) << "sequence_point.version_map() == " << sequence_point.version_map().Dump(); VLOG(1) << "effective_version == " << effective_version.Dump(); return shared_ptr<const LiveObject>(nullptr); } if (CanUseCachedLiveObject_Locked(sequence_point)) { CHECK(cached_live_object_.get() != nullptr); return cached_live_object_; } for (;;) { PeerThread peer_thread; peer_thread.Start(transaction_store_, shared_object_, shared_ptr<LiveObject>(nullptr), new_peer_objects); const bool success = ApplyTransactionsToWorkingVersion_Locked( &peer_thread, sequence_point, transactions_to_reject); peer_thread.Stop(); if (success) { return peer_thread.live_object(); } } return shared_ptr<const LiveObject>(nullptr); } void VersionedObjectContent::GetTransactions( const MaxVersionMap& transaction_store_version_map, map<TransactionId, linked_ptr<SharedObjectTransactionInfo>>* transactions, MaxVersionMap* effective_version) const { CHECK(transactions != nullptr); MutexLock lock(&committed_versions_mu_); for (const auto& transaction_pair : committed_versions_) { const TransactionId& transaction_id = transaction_pair.first; const SharedObjectTransaction& transaction = *transaction_pair.second; SharedObjectTransactionInfo* const transaction_info = new SharedObjectTransactionInfo(); const vector<linked_ptr<CommittedEvent>>& src_events = transaction.events(); vector<linked_ptr<CommittedEvent>>* const dest_events = &transaction_info->events; const vector<linked_ptr<CommittedEvent>>::size_type event_count = src_events.size(); dest_events->resize(event_count); for (vector<linked_ptr<CommittedEvent>>::size_type i = 0; i < event_count; ++i) { (*dest_events)[i].reset(src_events[i]->Clone()); } transaction_info->origin_peer = transaction.origin_peer(); CHECK(transactions->emplace(transaction_id, make_linked_ptr(transaction_info)).second); } ComputeEffectiveVersion_Locked(transaction_store_version_map, effective_version); } void VersionedObjectContent::StoreTransactions( const CanonicalPeer* origin_peer, map<TransactionId, linked_ptr<SharedObjectTransactionInfo>>* transactions, const MaxVersionMap& version_map) { CHECK(origin_peer != nullptr); CHECK(transactions != nullptr); MutexLock lock(&committed_versions_mu_); for (const auto& transaction_pair : *transactions) { const TransactionId& transaction_id = transaction_pair.first; SharedObjectTransactionInfo* const transaction_info = transaction_pair.second.get(); CHECK(IsValidTransactionId(transaction_id)); CHECK(transaction_info != nullptr); vector<linked_ptr<CommittedEvent>>* const events = &transaction_info->events; // TODO(dss): Rename this local variable to distinguish it from the // parameter 'origin_peer'. const CanonicalPeer* const origin_peer = transaction_info->origin_peer; CHECK(origin_peer != nullptr); linked_ptr<SharedObjectTransaction>& transaction = committed_versions_[transaction_id]; if (transaction.get() == nullptr) { transaction.reset(new SharedObjectTransaction(events, origin_peer)); } // TODO(dss): [BUG] The following statement should use the parameter named // 'origin_peer', not the local variable with the same name. version_map_.AddPeerTransactionId(origin_peer, transaction_id); } MaxVersionMap new_version_map; GetVersionMapUnion(version_map_, version_map, &new_version_map); version_map_.Swap(&new_version_map); up_to_date_peers_.insert(origin_peer); } void VersionedObjectContent::InsertTransaction( const CanonicalPeer* origin_peer, const TransactionId& transaction_id, vector<linked_ptr<CommittedEvent>>* events) { CHECK(origin_peer != nullptr); CHECK(IsValidTransactionId(transaction_id)); CHECK(events != nullptr); MutexLock lock(&committed_versions_mu_); linked_ptr<SharedObjectTransaction>& transaction = committed_versions_[transaction_id]; if (transaction.get() == nullptr) { transaction.reset(new SharedObjectTransaction(events, origin_peer)); } version_map_.AddPeerTransactionId(origin_peer, transaction_id); up_to_date_peers_.insert(origin_peer); } void VersionedObjectContent::SetCachedLiveObject( const shared_ptr<const LiveObject>& cached_live_object, const SequencePointImpl& cached_sequence_point) { CHECK(cached_live_object.get() != nullptr); MutexLock lock(&committed_versions_mu_); cached_live_object_ = cached_live_object; cached_sequence_point_.CopyFrom(cached_sequence_point); } string VersionedObjectContent::Dump() const { MutexLock lock(&committed_versions_mu_); string committed_versions_string; if (committed_versions_.empty()) { committed_versions_string = "{}"; } else { committed_versions_string = "{"; for (map<TransactionId, linked_ptr<SharedObjectTransaction>>::const_iterator it = committed_versions_.begin(); it != committed_versions_.end(); ++it) { if (it != committed_versions_.begin()) { committed_versions_string += ","; } StringAppendF(&committed_versions_string, " \"%s\": %s", TransactionIdToString(it->first).c_str(), it->second->Dump().c_str()); } committed_versions_string += " }"; } string up_to_date_peers_string; if (up_to_date_peers_.empty()) { up_to_date_peers_string = "[]"; } else { up_to_date_peers_string = "["; for (unordered_set<const CanonicalPeer*>::const_iterator it = up_to_date_peers_.begin(); it != up_to_date_peers_.end(); ++it) { if (it != up_to_date_peers_.begin()) { up_to_date_peers_string += ","; } StringAppendF(&up_to_date_peers_string, " \"%s\"", CEscape((*it)->peer_id()).c_str()); } up_to_date_peers_string += " ]"; } string cached_live_object_string; if (cached_live_object_.get() == nullptr) { cached_live_object_string = "null"; } else { cached_live_object_string = cached_live_object_->Dump(); } return StringPrintf( "{ \"committed_versions\": %s, \"version_map\": %s, " "\"up_to_date_peers\": %s, \"cached_live_object\": %s, " "\"cached_sequence_point\": %s }", committed_versions_string.c_str(), version_map_.Dump().c_str(), up_to_date_peers_string.c_str(), cached_live_object_string.c_str(), cached_sequence_point_.Dump().c_str()); } bool VersionedObjectContent::ApplyTransactionsToWorkingVersion_Locked( PeerThread* peer_thread, const SequencePointImpl& sequence_point, vector<pair<const CanonicalPeer*, TransactionId>>* transactions_to_reject) { CHECK(peer_thread != nullptr); CHECK(transactions_to_reject != nullptr); for (const auto& transaction_pair : committed_versions_) { const TransactionId& transaction_id = transaction_pair.first; const SharedObjectTransaction& transaction = *transaction_pair.second; const vector<linked_ptr<CommittedEvent>>& events = transaction.events(); if (!events.empty()) { const CanonicalPeer* const origin_peer = transaction.origin_peer(); if (sequence_point.HasPeerTransactionId(origin_peer, transaction_id) && FindTransactionIdInVector(*transactions_to_reject, transaction_id) == transactions_to_reject->end()) { for (const linked_ptr<CommittedEvent>& event : events) { peer_thread->QueueEvent(event.get()); } peer_thread->FlushEvents(); if (peer_thread->conflict_detected()) { transactions_to_reject->emplace_back(origin_peer, transaction_id); return false; } } } } return true; } void VersionedObjectContent::ComputeEffectiveVersion_Locked( const MaxVersionMap& transaction_store_version_map, MaxVersionMap* effective_version) const { CHECK(effective_version != nullptr); const unordered_map<const CanonicalPeer*, TransactionId>& version_map_peer_transaction_ids = version_map_.peer_transaction_ids(); for (const auto& version_map_pair : version_map_peer_transaction_ids) { effective_version->AddPeerTransactionId(version_map_pair.first, version_map_pair.second); } const unordered_map<const CanonicalPeer*, TransactionId>& transaction_store_peer_transaction_ids = transaction_store_version_map.peer_transaction_ids(); for (const CanonicalPeer* const origin_peer : up_to_date_peers_) { const unordered_map<const CanonicalPeer*, TransactionId>::const_iterator it2 = transaction_store_peer_transaction_ids.find(origin_peer); if (it2 != transaction_store_peer_transaction_ids.end()) { effective_version->AddPeerTransactionId(origin_peer, it2->second); } } } bool VersionedObjectContent::CanUseCachedLiveObject_Locked( const SequencePointImpl& requested_sequence_point) const { if (cached_live_object_.get() == nullptr) { return false; } const MaxVersionMap& requested_version_map = requested_sequence_point.version_map(); const MaxVersionMap& cached_version_map = cached_sequence_point_.version_map(); if (!VersionMapIsLessThanOrEqual(cached_version_map, requested_version_map)) { return false; } const unordered_map<const CanonicalPeer*, TransactionId>& requested_peer_transactions_ids = requested_version_map.peer_transaction_ids(); const unordered_map<const CanonicalPeer*, TransactionId>& cached_peer_transactions_ids = cached_version_map.peer_transaction_ids(); for (const auto& requested_peer_pair : requested_peer_transactions_ids) { const CanonicalPeer* const origin_peer = requested_peer_pair.first; const TransactionId& requested_transaction_id = requested_peer_pair.second; const unordered_map<const CanonicalPeer*, TransactionId>::const_iterator cached_peer_it = cached_peer_transactions_ids.find(origin_peer); TransactionId cached_transaction_id; if (cached_peer_it == cached_peer_transactions_ids.end()) { GetMinTransactionId(&cached_transaction_id); } else { cached_transaction_id.CopyFrom(cached_peer_it->second); } const map<TransactionId, linked_ptr<SharedObjectTransaction>>:: const_iterator start_it = committed_versions_.upper_bound( cached_transaction_id); const map<TransactionId, linked_ptr<SharedObjectTransaction>>:: const_iterator end_it = committed_versions_.upper_bound( requested_transaction_id); for (map<TransactionId, linked_ptr<SharedObjectTransaction>>::const_iterator transaction_it = start_it; transaction_it != end_it; ++transaction_it) { const SharedObjectTransaction& shared_object_transaction = *transaction_it->second; if (shared_object_transaction.origin_peer() == origin_peer) { const vector<linked_ptr<CommittedEvent>>& events = shared_object_transaction.events(); for (const linked_ptr<CommittedEvent>& event : events) { const CommittedEvent::Type event_type = event->type(); if (event_type != CommittedEvent::METHOD_CALL && event_type != CommittedEvent::SUB_METHOD_RETURN) { return false; } } } } } if (!PeerExclusionMapsAreEqual(requested_sequence_point.peer_exclusion_map(), cached_sequence_point_.peer_exclusion_map())) { return false; } if (requested_sequence_point.rejected_peers() != cached_sequence_point_.rejected_peers()) { return false; } return true; } } // namespace peer } // namespace floating_temple <|endoftext|>
<commit_before>//#define BLYNK_DEBUG #define BLYNK_PRINT Serial #include <wifi_config.h> #include <blynk_config.h> #include <BlynkSimpleEsp8266.h> #include <WiFiUdp.h> #include <NTPClient.h> #include <SimpleTimer.h> //******************************* //Define variable for Virtual Pins //******************************** long v0_masterswitch = 0; long v1_sleepinterval = 30; //Default start at 6 am int v2_irrigation_min_starttime = 6 * 3600; //Default stop at 7 pm int v2_irrigation_max_endtime = 19 * 3600; //V3 has no matching variable on purpose. Its a display text generated via value of V4 int v4_irrigation_last_dose = 0; int v5_irrigation_dosage_volume = 15; int v6_irrigation_dosage_interval = 2 * 3600; int v7_override =0; //******************************* //Define other variables //******************************** bool pump_running = false; WiFiUDP Udp; NTPClient ntpclient(Udp); bool isFirstConnect = true; SimpleTimer timer_sleep_esp; SimpleTimer timer_do_work; SimpleTimer timer_stop_pump; //******************************* //Define Constants //******************************** //Difference in seconds between Local time zone and UTC. //Use positive for East of 0 deg longitude and Negative for West of 0 deg longitude const int TIMEZONE_OFFSET = ((5*60) +30) * 60; const uint PUMP_PIN = 4; //Declare Function signature to avoid having the body before the call void dowork(); void sleep_timerfunc_interval() { BLYNK_LOG("Inside sleep_timerfunc_interval"); //Don't deep sleep if pump is running. if (pump_running) { BLYNK_LOG("Pump is running"); return; } BLYNK_LOG("Starting to Sleep for %d minutes", v1_sleepinterval); ESP.deepSleep(60 * v1_sleepinterval * 1000000,RF_DEFAULT); delay(1000); } void timerfunc_timeout_stop_pump() { //ESP.deepSleep(v1_sleepinterval * 60* 1000000,RF_DEFAULT); BLYNK_LOG("Stopping the Pump"); pump_running = false; digitalWrite(PUMP_PIN,LOW); } BLYNK_CONNECTED() { BLYNK_LOG("In BLYNK_CONNECTED"); if (isFirstConnect){ Blynk.syncAll(); isFirstConnect = false; BLYNK_LOG("Synced via BLYNK_CONNECTED"); } } BLYNK_WRITE(V0) // There is a Widget that WRITEs data to V0 { v0_masterswitch = param.asInt(); BLYNK_LOG("Change Master Switch is %d" , param.asInt()); } BLYNK_WRITE(V1) // There is a Widget that WRITEs data to V1 { v1_sleepinterval = param.asInt(); BLYNK_LOG("Change Sleep Interval is %d" , param.asInt()); } BLYNK_WRITE(V2) // There is a Widget that WRITEs data to V2 { TimeInputParam t(param); v2_irrigation_min_starttime = param[0].asInt(); v2_irrigation_max_endtime = param[1].asInt(); BLYNK_LOG ("Irrigation Start Time %d",v2_irrigation_min_starttime); BLYNK_LOG ("Irrigation Stop Time %d",v2_irrigation_max_endtime); } BLYNK_WRITE(V3) // There is a Widget that WRITEs data to V3 { BLYNK_LOG ("V3 is just a display text. It has no variable in h/w"); } BLYNK_WRITE(V4) // There is a Widget that WRITEs data to V4 { v4_irrigation_last_dose = param.asInt(); BLYNK_LOG ("Change Last watering time is %d",v4_irrigation_last_dose); } BLYNK_WRITE(V5) // There is a Widget that WRITEs data to V4 { v5_irrigation_dosage_volume = param.asInt(); BLYNK_LOG ("Change Time for watering is %d seconds",v5_irrigation_dosage_volume); } BLYNK_WRITE(V6) // There is a Widget that WRITEs data to V6 { v6_irrigation_dosage_interval = param.asInt(); BLYNK_LOG ("Change Delta between consecutive watering cycles is %d hours",v6_irrigation_dosage_interval); } BLYNK_WRITE(V7) // There is a Widget that WRITEs data to V4 { v7_override = param.asInt(); BLYNK_LOG ("Change Override Switch %d",v7_override); } void setup(/* arguments */) { /* code */ Serial.begin(115200); BLYNK_LOG("In setup"); pinMode(PUMP_PIN,OUTPUT); digitalWrite(PUMP_PIN, LOW); Blynk.begin(BLYNK_AUTH,WIFI_SSID,WIFI_PASSWORD); BLYNK_LOG("Waiting for BLYNK Server"); while (! Blynk.connected()) { BLYNK_LOG("."); } ntpclient.setTimeOffset(TIMEZONE_OFFSET); ntpclient.begin(); ntpclient.update(); BLYNK_LOG("Starting timer"); timer_sleep_esp.setInterval(30000L, sleep_timerfunc_interval); timer_do_work.setTimeout(10000L, dowork); } void loop(/* arguments */) { /* code */ //TODO /* Put code here to check for wifi and internet connectivity. Deep sleep for a long time if check fails to avoid battery wastage */ timer_sleep_esp.run(); Blynk.run(); timer_do_work.run(); if (pump_running) { timer_stop_pump.run(); } } void dowork() { BLYNK_LOG ("In dowork"); long now = ntpclient.getEpochTime(); //Check if we need to start the pump //get seconds from start of the day long seconds_since_start_of_day = (ntpclient.getHours() * 3600) + (ntpclient.getMinutes() * 60 ) + ntpclient.getSeconds(); BLYNK_LOG ("Last watering time is %d",v4_irrigation_last_dose); BLYNK_LOG ("Time between consecutive cycles %d",v6_irrigation_dosage_interval); BLYNK_LOG ("Seconds since start of day %d",seconds_since_start_of_day); if (v0_masterswitch == HIGH) { BLYNK_LOG ("Override is %d", v7_override); if ( v7_override or ( seconds_since_start_of_day >= (v4_irrigation_last_dose + v6_irrigation_dosage_interval))) { BLYNK_LOG ("Watering needed based on last dose and interval"); if (v7_override or ( ( seconds_since_start_of_day >= v2_irrigation_min_starttime ) and (seconds_since_start_of_day <= v2_irrigation_max_endtime))) { //BLYNK_LOG ("Current time is within min and max time window"); BLYNK_LOG ("Watering conditions met. Waterning now."); //All Conditions met. pump_running = true; digitalWrite(PUMP_PIN, HIGH); //Set the last watering time to current time to avoid this getting triggered again till the next cycle Blynk.virtualWrite(V4, seconds_since_start_of_day); v4_irrigation_last_dose = seconds_since_start_of_day; //Blynk.virtualWrite(V4, String(v4_irrigation_last_dose).c_str()); Blynk.virtualWrite(V4, v4_irrigation_last_dose); //Create a buffer to hold string HH:MM:SS char v3_display_buffer[10]; sprintf(v3_display_buffer, " %2d:%2d:%2d",ntpclient.getHours(), ntpclient.getMinutes() ,ntpclient.getSeconds()); Blynk.virtualWrite(V3, v3_display_buffer); BLYNK_LOG ("Last watering time in text %s",v3_display_buffer); timer_stop_pump.setTimeout( v5_irrigation_dosage_volume * 1000, timerfunc_timeout_stop_pump); } } } //Reset Override if (v7_override) { Blynk.virtualWrite(V7, 0); } } <commit_msg>Use epoch for time calculations<commit_after>//#define BLYNK_DEBUG #define BLYNK_PRINT Serial #include <wifi_config.h> #include <blynk_config.h> #include <BlynkSimpleEsp8266.h> #include <WiFiUdp.h> #include <NTPClient.h> #include <SimpleTimer.h> //******************************* //Define variable for Virtual Pins //******************************** long v0_masterswitch = 0; long v1_sleepinterval = 30; //Default start at 6 am int v2_irrigation_min_starttime = 6 * 3600; //Default stop at 7 pm int v2_irrigation_max_endtime = 19 * 3600; //V3 has no matching variable on purpose. Its a display text generated via value of V4 long v4_irrigation_last_dose = 0L; int v5_irrigation_dosage_volume = 15; int v6_irrigation_dosage_interval = 2 * 3600; int v7_override =0; //******************************* //Define other variables //******************************** bool pump_running = false; WiFiUDP Udp; NTPClient ntpclient(Udp); bool isFirstConnect = true; SimpleTimer timer_sleep_esp; SimpleTimer timer_do_work; SimpleTimer timer_stop_pump; //******************************* //Define Constants //******************************** //Difference in seconds between Local time zone and UTC. //Use positive for East of 0 deg longitude and Negative for West of 0 deg longitude const int TIMEZONE_OFFSET = ((5*60) +30) * 60; const uint PUMP_PIN = 4; //Declare Function signature to avoid having the body before the call void dowork(); void sleep_timerfunc_interval() { BLYNK_LOG("Inside sleep_timerfunc_interval"); //Don't deep sleep if pump is running. if (pump_running) { BLYNK_LOG("Pump is running"); return; } BLYNK_LOG("Starting to Sleep for %d minutes", v1_sleepinterval); ESP.deepSleep(60 * v1_sleepinterval * 1000000,RF_DEFAULT); delay(1000); } void timerfunc_timeout_stop_pump() { //ESP.deepSleep(v1_sleepinterval * 60* 1000000,RF_DEFAULT); BLYNK_LOG("Stopping the Pump"); pump_running = false; digitalWrite(PUMP_PIN,LOW); } BLYNK_CONNECTED() { BLYNK_LOG("In BLYNK_CONNECTED"); if (isFirstConnect){ Blynk.syncAll(); isFirstConnect = false; BLYNK_LOG("Synced via BLYNK_CONNECTED"); } } BLYNK_WRITE(V0) // There is a Widget that WRITEs data to V0 { v0_masterswitch = param.asInt(); BLYNK_LOG("Change Master Switch is %d" , param.asInt()); } BLYNK_WRITE(V1) // There is a Widget that WRITEs data to V1 { v1_sleepinterval = param.asInt(); BLYNK_LOG("Change Sleep Interval is %d" , param.asInt()); } BLYNK_WRITE(V2) // There is a Widget that WRITEs data to V2 { TimeInputParam t(param); v2_irrigation_min_starttime = param[0].asInt(); v2_irrigation_max_endtime = param[1].asInt(); BLYNK_LOG ("Irrigation Start Time %d",v2_irrigation_min_starttime); BLYNK_LOG ("Irrigation Stop Time %d",v2_irrigation_max_endtime); } BLYNK_WRITE(V3) // There is a Widget that WRITEs data to V3 { BLYNK_LOG ("V3 is just a display text. It has no variable in h/w"); } BLYNK_WRITE(V4) // There is a Widget that WRITEs data to V4 { v4_irrigation_last_dose = param.asLong(); BLYNK_LOG ("Change Last watering time is %ld",v4_irrigation_last_dose); } BLYNK_WRITE(V5) // There is a Widget that WRITEs data to V4 { v5_irrigation_dosage_volume = param.asInt(); BLYNK_LOG ("Change Time for watering is %d seconds",v5_irrigation_dosage_volume); } BLYNK_WRITE(V6) // There is a Widget that WRITEs data to V6 { v6_irrigation_dosage_interval = param.asInt(); BLYNK_LOG ("Change Delta between consecutive watering cycles is %d hours",v6_irrigation_dosage_interval); } BLYNK_WRITE(V7) // There is a Widget that WRITEs data to V4 { v7_override = param.asInt(); BLYNK_LOG ("Change Override Switch %d",v7_override); } void setup(/* arguments */) { /* code */ Serial.begin(115200); BLYNK_LOG("In setup"); pinMode(PUMP_PIN,OUTPUT); digitalWrite(PUMP_PIN, LOW); Blynk.begin(BLYNK_AUTH,WIFI_SSID,WIFI_PASSWORD); BLYNK_LOG("Waiting for BLYNK Server"); while (! Blynk.connected()) { BLYNK_LOG("."); } ntpclient.setTimeOffset(TIMEZONE_OFFSET); ntpclient.begin(); ntpclient.update(); BLYNK_LOG("Starting timer"); timer_sleep_esp.setInterval(30000L, sleep_timerfunc_interval); timer_do_work.setTimeout(10000L, dowork); } void loop(/* arguments */) { /* code */ //TODO /* Put code here to check for wifi and internet connectivity. Deep sleep for a long time if check fails to avoid battery wastage */ timer_sleep_esp.run(); Blynk.run(); timer_do_work.run(); if (pump_running) { timer_stop_pump.run(); } } void dowork() { BLYNK_LOG ("In dowork"); long now = ntpclient.getEpochTime(); //Check if we need to start the pump //get epoch long epoch = ntpclient.getEpochTime(); //get seconds from start of the day int seconds_since_start_of_day = epoch % 86400; BLYNK_LOG ("Epoch is %ld",epoch); BLYNK_LOG ("Last watering time is %ld",v4_irrigation_last_dose); BLYNK_LOG ("Time between consecutive cycles %d",v6_irrigation_dosage_interval); BLYNK_LOG ("Seconds since start of day %d",seconds_since_start_of_day); if (v0_masterswitch == HIGH) { BLYNK_LOG ("Override is %d", v7_override); if ( v7_override or ( epoch >= (v4_irrigation_last_dose + v6_irrigation_dosage_interval))) { BLYNK_LOG ("Watering needed based on last dose and interval"); if (v7_override or ( ( seconds_since_start_of_day >= v2_irrigation_min_starttime ) and (seconds_since_start_of_day <= v2_irrigation_max_endtime))) { //BLYNK_LOG ("Current time is within min and max time window"); BLYNK_LOG ("Watering conditions met. Waterning now."); //All Conditions met. pump_running = true; digitalWrite(PUMP_PIN, HIGH); //Set the last watering time to current time to avoid this getting triggered again till the next cycle v4_irrigation_last_dose = epoch; Blynk.virtualWrite(V4, v4_irrigation_last_dose); //Create a buffer to hold string HH:MM:SS //char v3_display_buffer[10]; //sprintf(v3_display_buffer, "%02d:%02d:%02d",ntpclient.getHours(), ntpclient.getMinutes() ,ntpclient.getSeconds()); String v3_display_buffer; v3_display_buffer = ntpclient.getFormattedTime(); Blynk.virtualWrite(V3, v3_display_buffer); BLYNK_LOG ("Last watering time in text %s",v3_display_buffer.c_str()); timer_stop_pump.setTimeout( v5_irrigation_dosage_volume * 1000, timerfunc_timeout_stop_pump); } } } //Reset Override if (v7_override) { Blynk.virtualWrite(V7, 0); } } <|endoftext|>
<commit_before>// *************************************************************************** // FastaIndex.cpp (c) 2010 Erik Garrison <erik.garrison@bc.edu> // Marth Lab, Department of Biology, Boston College // All rights reserved. // --------------------------------------------------------------------------- // Last modified: 9 February 2010 (EG) // --------------------------------------------------------------------------- #include "Fasta.h" FastaIndexEntry::FastaIndexEntry(string name, int length, long long offset, int line_blen, int line_len) : name(name) , length(length) , offset(offset) , line_blen(line_blen) , line_len(line_len) {} FastaIndexEntry::FastaIndexEntry(void) // empty constructor { clear(); } FastaIndexEntry::~FastaIndexEntry(void) {} void FastaIndexEntry::clear(void) { name = ""; length = 0; offset = -1; // no real offset will ever be below 0, so this allows us to // check if we have already recorded a real offset line_blen = 0; line_len = 0; } ostream& operator<<(ostream& output, const FastaIndexEntry& e) { // just write the first component of the name, for compliance with other tools output << split(e.name, ' ').at(0) << "\t" << e.length << "\t" << e.offset << "\t" << e.line_blen << "\t" << e.line_len; return output; // for multiple << operators. } FastaIndex::FastaIndex(void) {} void FastaIndex::readIndexFile(string fname) { string line; long long linenum = 0; indexFile.open(fname.c_str(), ifstream::in); if (indexFile.is_open()) { while (getline (indexFile, line)) { ++linenum; // the fai format defined in samtools is tab-delimited, every line being: // fai->name[i], (int)x.len, (long long)x.offset, (int)x.line_blen, (int)x.line_len vector<string> fields = split(line, '\t'); if (fields.size() == 5) { // if we don't get enough fields then there is a problem with the file // note that fields[0] is the sequence name char* end; string name = split(fields[0], " \t").at(0); // key by first token of name sequenceNames.push_back(name); this->insert(make_pair(name, FastaIndexEntry(fields[0], atoi(fields[1].c_str()), strtoll(fields[2].c_str(), &end, 10), atoi(fields[3].c_str()), atoi(fields[4].c_str())))); } else { cerr << "Warning: malformed fasta index file " << fname << "does not have enough fields @ line " << linenum << endl; cerr << line << endl; exit(1); } } } else { cerr << "could not open index file " << fname << endl; exit(1); } } // for consistency this should be a class method bool fastaIndexEntryCompare ( FastaIndexEntry a, FastaIndexEntry b) { return (a.offset<b.offset); } ostream& operator<<(ostream& output, FastaIndex& fastaIndex) { vector<FastaIndexEntry> sortedIndex; for(vector<string>::const_iterator it = fastaIndex.sequenceNames.begin(); it != fastaIndex.sequenceNames.end(); ++it) { sortedIndex.push_back(fastaIndex[*it]); } sort(sortedIndex.begin(), sortedIndex.end(), fastaIndexEntryCompare); for( vector<FastaIndexEntry>::iterator fit = sortedIndex.begin(); fit != sortedIndex.end(); ++fit) { output << *fit << endl; } } void FastaIndex::indexReference(string refname) { // overview: // for line in the reference fasta file // track byte offset from the start of the file // if line is a fasta header, take the name and dump the last sequnece to the index // if line is a sequence, add it to the current sequence //cerr << "indexing fasta reference " << refname << endl; string line; FastaIndexEntry entry; // an entry buffer used in processing entry.clear(); int line_length = 0; long long offset = 0; // byte offset from start of file long long line_number = 0; // current line number bool mismatchedLineLengths = false; // flag to indicate if our line length changes mid-file // this will be used to raise an error // if we have a line length change at // any line other than the last line in // the sequence bool emptyLine = false; // flag to catch empty lines, which we allow for // index generation only on the last line of the sequence ifstream refFile; refFile.open(refname.c_str()); if (refFile.is_open()) { while (getline(refFile, line)) { ++line_number; line_length = line.length(); if (line[0] == ';') { // fasta comment, skip } else if (line[0] == '+') { // fastq quality header getline(refFile, line); line_length = line.length(); offset += line_length + 1; // get and don't handle the quality line getline(refFile, line); line_length = line.length(); } else if (line[0] == '>' || line[0] == '@') { // fasta /fastq header // if we aren't on the first entry, push the last sequence into the index if (entry.name != "") { mismatchedLineLengths = false; // reset line length error tracker for every new sequence emptyLine = false; flushEntryToIndex(entry); entry.clear(); } entry.name = line.substr(1, line_length - 1); } else { // we assume we have found a sequence line if (entry.offset == -1) // NB initially the offset is -1 entry.offset = offset; entry.length += line_length; if (entry.line_len) { //entry.line_len = entry.line_len ? entry.line_len : line_length + 1; if (mismatchedLineLengths || emptyLine) { if (line_length == 0) { emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence } else { if (emptyLine) { cerr << "ERROR: embedded newline"; } else { cerr << "ERROR: mismatched line lengths"; } cerr << " at line " << line_number << " within sequence " << entry.name << endl << "File not suitable for fasta index generation." << endl; exit(1); } } // this flag is set here and checked on the next line // because we may have reached the end of the sequence, in // which case a mismatched line length is OK if (entry.line_len != line_length + 1) { mismatchedLineLengths = true; if (line_length == 0) { emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence } } } else { entry.line_len = line_length + 1; // first line } entry.line_blen = entry.line_len - 1; } offset += line_length + 1; } // we've hit the end of the fasta file! // flush the last entry flushEntryToIndex(entry); } else { cerr << "could not open reference file " << refname << " for indexing!" << endl; exit(1); } } void FastaIndex::flushEntryToIndex(FastaIndexEntry& entry) { string name = split(entry.name, " \t").at(0); // key by first token of name sequenceNames.push_back(name); this->insert(make_pair(name, FastaIndexEntry(entry.name, entry.length, entry.offset, entry.line_blen, entry.line_len))); } void FastaIndex::writeIndexFile(string fname) { //cerr << "writing fasta index file " << fname << endl; ofstream file; file.open(fname.c_str()); if (file.is_open()) { file << *this; } else { cerr << "could not open index file " << fname << " for writing!" << endl; exit(1); } } FastaIndex::~FastaIndex(void) { indexFile.close(); } FastaIndexEntry FastaIndex::entry(string name) { FastaIndex::iterator e = this->find(name); if (e == this->end()) { cerr << "unable to find FASTA index entry for '" << name << "'" << endl; exit(1); } else { return e->second; } } string FastaIndex::indexFileExtension() { return ".fai"; } /* FastaReference::FastaReference(string reffilename) { } */ void FastaReference::open(string reffilename) { filename = reffilename; if (!(file = fopen(filename.c_str(), "r"))) { cerr << "could not open " << filename << endl; exit(1); } index = new FastaIndex(); struct stat stFileInfo; string indexFileName = filename + index->indexFileExtension(); // if we can find an index file, use it if(stat(indexFileName.c_str(), &stFileInfo) == 0) { index->readIndexFile(indexFileName); } else { // otherwise, read the reference and generate the index file in the cwd cerr << "index file " << indexFileName << " not found, generating..." << endl; index->indexReference(filename); index->writeIndexFile(indexFileName); } } FastaReference::~FastaReference(void) { fclose(file); delete index; } string FastaReference::getSequence(string seqname) { FastaIndexEntry entry = index->entry(seqname); int newlines_in_sequence = entry.length / entry.line_blen; int seqlen = newlines_in_sequence + entry.length; char* seq = (char*) calloc (seqlen + 1, sizeof(char)); fseek64(file, entry.offset, SEEK_SET); fread(seq, sizeof(char), seqlen, file); seq[seqlen] = '\0'; char* pbegin = seq; char* pend = seq + (seqlen/sizeof(char)); pend = remove(pbegin, pend, '\n'); pend = remove(pbegin, pend, '\0'); string s = seq; free(seq); s.resize((pend - pbegin)/sizeof(char)); return s; } // TODO cleanup; odd function. use a map string FastaReference::sequenceNameStartingWith(string seqnameStart) { try { return (*index)[seqnameStart].name; } catch (exception& e) { cerr << e.what() << ": unable to find index entry for " << seqnameStart << endl; exit(1); } } string FastaReference::getSubSequence(string seqname, int start, int length) { FastaIndexEntry entry = index->entry(seqname); length = min(length, entry.length - start); if (start < 0 || length < 1) { return ""; } // we have to handle newlines // approach: count newlines before start // count newlines by end of read // subtracting newlines before start find count of embedded newlines int newlines_before = start > 0 ? (start - 1) / entry.line_blen : 0; int newlines_by_end = (start + length - 1) / entry.line_blen; int newlines_inside = newlines_by_end - newlines_before; int seqlen = length + newlines_inside; char* seq = (char*) calloc (seqlen + 1, sizeof(char)); fseek64(file, (off_t) (entry.offset + newlines_before + start), SEEK_SET); fread(seq, sizeof(char), (off_t) seqlen, file); seq[seqlen] = '\0'; char* pbegin = seq; char* pend = seq + (seqlen/sizeof(char)); pend = remove(pbegin, pend, '\n'); pend = remove(pbegin, pend, '\0'); string s = seq; free(seq); s.resize((pend - pbegin)/sizeof(char)); return s; } long unsigned int FastaReference::sequenceLength(string seqname) { FastaIndexEntry entry = index->entry(seqname); return entry.length; } <commit_msg>VCF's should not include IUPAC bases in the REF column.<commit_after>// *************************************************************************** // FastaIndex.cpp (c) 2010 Erik Garrison <erik.garrison@bc.edu> // Marth Lab, Department of Biology, Boston College // All rights reserved. // --------------------------------------------------------------------------- // Last modified: 9 February 2010 (EG) // --------------------------------------------------------------------------- #include "Fasta.h" FastaIndexEntry::FastaIndexEntry(string name, int length, long long offset, int line_blen, int line_len) : name(name) , length(length) , offset(offset) , line_blen(line_blen) , line_len(line_len) {} FastaIndexEntry::FastaIndexEntry(void) // empty constructor { clear(); } FastaIndexEntry::~FastaIndexEntry(void) {} void FastaIndexEntry::clear(void) { name = ""; length = 0; offset = -1; // no real offset will ever be below 0, so this allows us to // check if we have already recorded a real offset line_blen = 0; line_len = 0; } ostream& operator<<(ostream& output, const FastaIndexEntry& e) { // just write the first component of the name, for compliance with other tools output << split(e.name, ' ').at(0) << "\t" << e.length << "\t" << e.offset << "\t" << e.line_blen << "\t" << e.line_len; return output; // for multiple << operators. } FastaIndex::FastaIndex(void) {} void FastaIndex::readIndexFile(string fname) { string line; long long linenum = 0; indexFile.open(fname.c_str(), ifstream::in); if (indexFile.is_open()) { while (getline (indexFile, line)) { ++linenum; // the fai format defined in samtools is tab-delimited, every line being: // fai->name[i], (int)x.len, (long long)x.offset, (int)x.line_blen, (int)x.line_len vector<string> fields = split(line, '\t'); if (fields.size() == 5) { // if we don't get enough fields then there is a problem with the file // note that fields[0] is the sequence name char* end; string name = split(fields[0], " \t").at(0); // key by first token of name sequenceNames.push_back(name); this->insert(make_pair(name, FastaIndexEntry(fields[0], atoi(fields[1].c_str()), strtoll(fields[2].c_str(), &end, 10), atoi(fields[3].c_str()), atoi(fields[4].c_str())))); } else { cerr << "Warning: malformed fasta index file " << fname << "does not have enough fields @ line " << linenum << endl; cerr << line << endl; exit(1); } } } else { cerr << "could not open index file " << fname << endl; exit(1); } } // for consistency this should be a class method bool fastaIndexEntryCompare ( FastaIndexEntry a, FastaIndexEntry b) { return (a.offset<b.offset); } ostream& operator<<(ostream& output, FastaIndex& fastaIndex) { vector<FastaIndexEntry> sortedIndex; for(vector<string>::const_iterator it = fastaIndex.sequenceNames.begin(); it != fastaIndex.sequenceNames.end(); ++it) { sortedIndex.push_back(fastaIndex[*it]); } sort(sortedIndex.begin(), sortedIndex.end(), fastaIndexEntryCompare); for( vector<FastaIndexEntry>::iterator fit = sortedIndex.begin(); fit != sortedIndex.end(); ++fit) { output << *fit << endl; } } void FastaIndex::indexReference(string refname) { // overview: // for line in the reference fasta file // track byte offset from the start of the file // if line is a fasta header, take the name and dump the last sequnece to the index // if line is a sequence, add it to the current sequence //cerr << "indexing fasta reference " << refname << endl; string line; FastaIndexEntry entry; // an entry buffer used in processing entry.clear(); int line_length = 0; long long offset = 0; // byte offset from start of file long long line_number = 0; // current line number bool mismatchedLineLengths = false; // flag to indicate if our line length changes mid-file // this will be used to raise an error // if we have a line length change at // any line other than the last line in // the sequence bool emptyLine = false; // flag to catch empty lines, which we allow for // index generation only on the last line of the sequence ifstream refFile; refFile.open(refname.c_str()); if (refFile.is_open()) { while (getline(refFile, line)) { ++line_number; line_length = line.length(); if (line[0] == ';') { // fasta comment, skip } else if (line[0] == '+') { // fastq quality header getline(refFile, line); line_length = line.length(); offset += line_length + 1; // get and don't handle the quality line getline(refFile, line); line_length = line.length(); } else if (line[0] == '>' || line[0] == '@') { // fasta /fastq header // if we aren't on the first entry, push the last sequence into the index if (entry.name != "") { mismatchedLineLengths = false; // reset line length error tracker for every new sequence emptyLine = false; flushEntryToIndex(entry); entry.clear(); } entry.name = line.substr(1, line_length - 1); } else { // we assume we have found a sequence line if (entry.offset == -1) // NB initially the offset is -1 entry.offset = offset; entry.length += line_length; if (entry.line_len) { //entry.line_len = entry.line_len ? entry.line_len : line_length + 1; if (mismatchedLineLengths || emptyLine) { if (line_length == 0) { emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence } else { if (emptyLine) { cerr << "ERROR: embedded newline"; } else { cerr << "ERROR: mismatched line lengths"; } cerr << " at line " << line_number << " within sequence " << entry.name << endl << "File not suitable for fasta index generation." << endl; exit(1); } } // this flag is set here and checked on the next line // because we may have reached the end of the sequence, in // which case a mismatched line length is OK if (entry.line_len != line_length + 1) { mismatchedLineLengths = true; if (line_length == 0) { emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence } } } else { entry.line_len = line_length + 1; // first line } entry.line_blen = entry.line_len - 1; } offset += line_length + 1; } // we've hit the end of the fasta file! // flush the last entry flushEntryToIndex(entry); } else { cerr << "could not open reference file " << refname << " for indexing!" << endl; exit(1); } } void FastaIndex::flushEntryToIndex(FastaIndexEntry& entry) { string name = split(entry.name, " \t").at(0); // key by first token of name sequenceNames.push_back(name); this->insert(make_pair(name, FastaIndexEntry(entry.name, entry.length, entry.offset, entry.line_blen, entry.line_len))); } void FastaIndex::writeIndexFile(string fname) { //cerr << "writing fasta index file " << fname << endl; ofstream file; file.open(fname.c_str()); if (file.is_open()) { file << *this; } else { cerr << "could not open index file " << fname << " for writing!" << endl; exit(1); } } FastaIndex::~FastaIndex(void) { indexFile.close(); } FastaIndexEntry FastaIndex::entry(string name) { FastaIndex::iterator e = this->find(name); if (e == this->end()) { cerr << "unable to find FASTA index entry for '" << name << "'" << endl; exit(1); } else { return e->second; } } string FastaIndex::indexFileExtension() { return ".fai"; } /* FastaReference::FastaReference(string reffilename) { } */ void FastaReference::open(string reffilename) { filename = reffilename; if (!(file = fopen(filename.c_str(), "r"))) { cerr << "could not open " << filename << endl; exit(1); } index = new FastaIndex(); struct stat stFileInfo; string indexFileName = filename + index->indexFileExtension(); // if we can find an index file, use it if(stat(indexFileName.c_str(), &stFileInfo) == 0) { index->readIndexFile(indexFileName); } else { // otherwise, read the reference and generate the index file in the cwd cerr << "index file " << indexFileName << " not found, generating..." << endl; index->indexReference(filename); index->writeIndexFile(indexFileName); } } FastaReference::~FastaReference(void) { fclose(file); delete index; } string removeIupac(string& str) { for (int i=0; i<str.length(); ++i) { char c = str[i]; if (c != 'A' && c != 'T' && c != 'G' && c != 'C' && c != 'N' && c != 'a' && c != 't' && c != 'g' && c != 'c' && c != 'n') { str[i] = 'N'; } } return str; } string FastaReference::getSequence(string seqname) { FastaIndexEntry entry = index->entry(seqname); int newlines_in_sequence = entry.length / entry.line_blen; int seqlen = newlines_in_sequence + entry.length; char* seq = (char*) calloc (seqlen + 1, sizeof(char)); fseek64(file, entry.offset, SEEK_SET); fread(seq, sizeof(char), seqlen, file); seq[seqlen] = '\0'; char* pbegin = seq; char* pend = seq + (seqlen/sizeof(char)); pend = remove(pbegin, pend, '\n'); pend = remove(pbegin, pend, '\0'); string s = seq; free(seq); s.resize((pend - pbegin)/sizeof(char)); return removeIupac(s); } // TODO cleanup; odd function. use a map string FastaReference::sequenceNameStartingWith(string seqnameStart) { try { return (*index)[seqnameStart].name; } catch (exception& e) { cerr << e.what() << ": unable to find index entry for " << seqnameStart << endl; exit(1); } } string FastaReference::getSubSequence(string seqname, int start, int length) { FastaIndexEntry entry = index->entry(seqname); length = min(length, entry.length - start); if (start < 0 || length < 1) { return ""; } // we have to handle newlines // approach: count newlines before start // count newlines by end of read // subtracting newlines before start find count of embedded newlines int newlines_before = start > 0 ? (start - 1) / entry.line_blen : 0; int newlines_by_end = (start + length - 1) / entry.line_blen; int newlines_inside = newlines_by_end - newlines_before; int seqlen = length + newlines_inside; char* seq = (char*) calloc (seqlen + 1, sizeof(char)); fseek64(file, (off_t) (entry.offset + newlines_before + start), SEEK_SET); fread(seq, sizeof(char), (off_t) seqlen, file); seq[seqlen] = '\0'; char* pbegin = seq; char* pend = seq + (seqlen/sizeof(char)); pend = remove(pbegin, pend, '\n'); pend = remove(pbegin, pend, '\0'); string s = seq; free(seq); s.resize((pend - pbegin)/sizeof(char)); return removeIupac(s); } long unsigned int FastaReference::sequenceLength(string seqname) { FastaIndexEntry entry = index->entry(seqname); return entry.length; } <|endoftext|>
<commit_before>// // Copyright (C) 2014 // Alessio Sclocco <a.sclocco@vu.nl> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #include <iostream> using std::cout; using std::cerr; using std::endl; using std::fixed; #include <iomanip> using std::setprecision; #include <ctime> #include <ArgumentList.hpp> using isa::utils::ArgumentList; #include <InitializeOpenCL.hpp> using isa::OpenCL::initializeOpenCL; #include <CLData.hpp> using isa::OpenCL::CLData; #include <Exceptions.hpp> using isa::Exceptions::OpenCLError; #include <Flops.hpp> using isa::Benchmarks::Flops; #include <utils.hpp> using isa::utils::same; const unsigned int nrIterations = 10; const unsigned int nrLoops = 100; int main(int argc, char * argv[]) { unsigned int oclPlatform = 0; unsigned int oclDevice = 0; unsigned int arrayDim = 0; unsigned int minThreads = 0; unsigned int maxThreads = 0; // Parse command line if ( argc != 9 ) { cerr << "Usage: " << argv[0] << " -opencl_platform <opencl_platform> -opencl_device <opencl_device> -min <min_threads> -max <max_threads>" << endl; return 1; } ArgumentList commandLine(argc, argv); try { oclPlatform = commandLine.getSwitchArgument< unsigned int >("-opencl_platform"); oclDevice = commandLine.getSwitchArgument< unsigned int >("-opencl_device"); minThreads = commandLine.getSwitchArgument< unsigned int >("-min"); maxThreads = commandLine.getSwitchArgument< unsigned int >("-max"); } catch ( exception & err ) { cerr << err.what() << endl; return 1; } // Initialize OpenCL vector< cl::Platform > * oclPlatforms = new vector< cl::Platform >(); cl::Context * oclContext = new cl::Context(); vector< cl::Device > * oclDevices = new vector< cl::Device >(); vector< vector< cl::CommandQueue > > * oclQueues = new vector< vector< cl::CommandQueue > >(); try { initializeOpenCL(oclPlatform, 1, oclPlatforms, oclContext, oclDevices, oclQueues); } catch ( OpenCLError err ) { cerr << err.what() << endl; return 1; } arrayDim = (oclDevices->at(oclDevice)).getInfo< CL_DEVICE_MAX_MEM_ALLOC_SIZE >(); arrayDim /= sizeof(float); CLData< float > * A = new CLData< float >("A", true); CLData< float > * C = new CLData< float >("C", true); A->setCLContext(oclContext); A->setCLQueue(&(oclQueues->at(oclDevice)[0])); A->allocateHostData(arrayDim); srand(time(NULL)); for ( unsigned int i = 0; i < arrayDim; i++ ) { A->setHostDataItem(i, 1.0f / static_cast< float >(rand() % 15)); } C->setCLContext(oclContext); C->setCLQueue(&(oclQueues->at(oclDevice)[0])); C->allocateHostData(arrayDim); try { A->setDeviceReadOnly(); A->allocateDeviceData(); A->copyHostToDevice(); C->setDeviceWriteOnly(); C->allocateDeviceData(); } catch ( OpenCLError err ) { cerr << err.what() << endl; return 1; } cout << fixed << setprecision(3) << endl; for (unsigned int threads0 = minThreads; threads0 <= maxThreads; threads0 *= 2 ) { for (unsigned int threads1 = 1; threads1 <= 32; threads1++ ) { if ( (arrayDim % (threads0 * threads1) != 0) || ((threads0 * threads1) > maxThreads) ) { continue; } Flops< float > flops = Flops< float >("float"); try { flops.bindOpenCL(oclContext, &(oclDevices->at(oclDevice)), &(oclQueues->at(oclDevice)[0])); flops.setNrThreads(arrayDim); flops.setNrThreadsPerBlock(threads0); flops.setNrRows(threads1); flops.setNrIterations(nrLoops); flops.generateCode(); flops(A, C); (flops.getTimer()).reset(); for ( unsigned int iter = 0; iter < nrIterations; iter++ ) { flops(A, C); } } catch ( OpenCLError err ) { cerr << err.what() << endl; return 1; } cout << threads0 << " " << threads1 << " " << flops.getGFLOPs() << " " << flops.getGBs() << endl; } } cout << endl; return 0; } <commit_msg>The number of kernel loop iterations is defined at runtime.<commit_after>// // Copyright (C) 2014 // Alessio Sclocco <a.sclocco@vu.nl> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #include <iostream> using std::cout; using std::cerr; using std::endl; using std::fixed; #include <iomanip> using std::setprecision; #include <ctime> #include <ArgumentList.hpp> using isa::utils::ArgumentList; #include <InitializeOpenCL.hpp> using isa::OpenCL::initializeOpenCL; #include <CLData.hpp> using isa::OpenCL::CLData; #include <Exceptions.hpp> using isa::Exceptions::OpenCLError; #include <Flops.hpp> using isa::Benchmarks::Flops; #include <utils.hpp> using isa::utils::same; const unsigned int nrIterations = 10; int main(int argc, char * argv[]) { unsigned int oclPlatform = 0; unsigned int oclDevice = 0; unsigned int arrayDim = 0; unsigned int nrLoops = 0; unsigned int minThreads = 0; unsigned int maxThreads = 0; // Parse command line if ( argc != 11 ) { cerr << "Usage: " << argv[0] << " -opencl_platform <opencl_platform> -opencl_device <opencl_device> -loops <nr_loops> -min <min_threads> -max <max_threads>" << endl; return 1; } ArgumentList commandLine(argc, argv); try { oclPlatform = commandLine.getSwitchArgument< unsigned int >("-opencl_platform"); oclDevice = commandLine.getSwitchArgument< unsigned int >("-opencl_device"); nrLoops = commandLine.getSwitchArgument< unsigned int >("-loops"); minThreads = commandLine.getSwitchArgument< unsigned int >("-min"); maxThreads = commandLine.getSwitchArgument< unsigned int >("-max"); } catch ( exception & err ) { cerr << err.what() << endl; return 1; } // Initialize OpenCL vector< cl::Platform > * oclPlatforms = new vector< cl::Platform >(); cl::Context * oclContext = new cl::Context(); vector< cl::Device > * oclDevices = new vector< cl::Device >(); vector< vector< cl::CommandQueue > > * oclQueues = new vector< vector< cl::CommandQueue > >(); try { initializeOpenCL(oclPlatform, 1, oclPlatforms, oclContext, oclDevices, oclQueues); } catch ( OpenCLError err ) { cerr << err.what() << endl; return 1; } arrayDim = (oclDevices->at(oclDevice)).getInfo< CL_DEVICE_MAX_MEM_ALLOC_SIZE >(); arrayDim /= sizeof(float); CLData< float > * A = new CLData< float >("A", true); CLData< float > * C = new CLData< float >("C", true); A->setCLContext(oclContext); A->setCLQueue(&(oclQueues->at(oclDevice)[0])); A->allocateHostData(arrayDim); srand(time(NULL)); for ( unsigned int i = 0; i < arrayDim; i++ ) { A->setHostDataItem(i, 1.0f / static_cast< float >(rand() % 15)); } C->setCLContext(oclContext); C->setCLQueue(&(oclQueues->at(oclDevice)[0])); C->allocateHostData(arrayDim); try { A->setDeviceReadOnly(); A->allocateDeviceData(); A->copyHostToDevice(); C->setDeviceWriteOnly(); C->allocateDeviceData(); } catch ( OpenCLError err ) { cerr << err.what() << endl; return 1; } cout << fixed << setprecision(3) << endl; for (unsigned int threads0 = minThreads; threads0 <= maxThreads; threads0 *= 2 ) { for (unsigned int threads1 = 1; threads1 <= 32; threads1++ ) { if ( (arrayDim % (threads0 * threads1) != 0) || ((threads0 * threads1) > maxThreads) ) { continue; } Flops< float > flops = Flops< float >("float"); try { flops.bindOpenCL(oclContext, &(oclDevices->at(oclDevice)), &(oclQueues->at(oclDevice)[0])); flops.setNrThreads(arrayDim); flops.setNrThreadsPerBlock(threads0); flops.setNrRows(threads1); flops.setNrIterations(nrLoops); flops.generateCode(); flops(A, C); (flops.getTimer()).reset(); for ( unsigned int iter = 0; iter < nrIterations; iter++ ) { flops(A, C); } } catch ( OpenCLError err ) { cerr << err.what() << endl; return 1; } cout << threads0 << " " << threads1 << " " << flops.getGFLOPs() << " " << flops.getGBs() << endl; } } cout << endl; return 0; } <|endoftext|>
<commit_before>#include "Graph.h" const int BLACK = 0x00; Graph::Graph(Screen* s, int sca) { screen = s; scale = sca; width = s->width; height = s->height; origin[0] = width/2; origin[1] = height/2; in = new InputMan(); running = true; } Graph::~Graph(void) { } int units(){[1] return {(origin[0]/scale), (origin[1]/scale)}; } int (*to_graph(int x, int y))[1] { return *{origin[0]+(x*units()[0]), origin[1]-(y*units()[1])}; } int (*from_graph(int x, int y))[1] { return *{((x-origin[0])/units[0]), -((origin[1]-y)/units[1])}; } void Graph::update() { input(); draw_axis(); for (int i = 0; i < origin[0]; ++i) { if ((i % scale) == 0) { // x = 0, y > 0 screen->set_pixel(origin[0] + 2, origin[1] - i, BLACK); screen->set_pixel(origin[0] + 1, origin[1] - i, BLACK); screen->set_pixel(origin[0] - 1, origin[1] - i, BLACK); screen->set_pixel(origin[0] - 2, origin[1] - i, BLACK); // x = 0, y < 0 screen->set_pixel(origin[0] + 2, i + origin[1], BLACK); screen->set_pixel(origin[0] + 1, i + origin[1], BLACK); screen->set_pixel(origin[0] - 1, i + origin[1], BLACK); screen->set_pixel(origin[0] - 2, i + origin[1], BLACK); // y = 0, x > 0 screen->set_pixel(origin[0] - i, origin[1] + 2, BLACK); screen->set_pixel(origin[0] - i, origin[1] + 1, BLACK); screen->set_pixel(origin[0] - i, origin[1] - 1, BLACK); screen->set_pixel(origin[0] - i, origin[1] - 2, BLACK); // y = 0, x < 0 screen->set_pixel(i + origin[0], origin[1] + 2, BLACK); screen->set_pixel(i + origin[0], origin[1] + 1, BLACK); screen->set_pixel(i + origin[0], origin[1] - 1, BLACK); screen->set_pixel(i + origin[0], origin[1] - 2, BLACK); } } } void Graph::draw_axis() { screen->draw_line(origin[0], 0, origin[0], height, BLACK); screen->draw_line(0, origin[1], width, origin[1], BLACK); } void Graph::input() { SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: running = false; break; case SDL_KEYDOWN: in->set_key_down(event.key.keysym.sym); break; case SDL_KEYUP: in->set_key_up(event.key.keysym.sym); break; } } if (in->get_key(SDLK_ESCAPE)) running = false; if (in->get_key(SDLK_MINUS)) zoom_out(); if (in->get_key(SDLK_EQUALS)) zoom_in(); } void Graph::zoom_in() { if (scale < origin[0]) scale += 1; } void Graph::zoom_out() { if (scale > 2) scale -= 1; } <commit_msg>Forgotten Graph:: .<commit_after>#include "Graph.h" const int BLACK = 0x00; Graph::Graph(Screen* s, int sca) { screen = s; scale = sca; width = s->width; height = s->height; origin[0] = width/2; origin[1] = height/2; in = new InputMan(); running = true; } Graph::~Graph(void) { } int Graph::units(){[1] return {(origin[0]/scale), (origin[1]/scale)}; } int (*Graph::to_graph(int x, int y))[1] { return *{origin[0]+(x*units()[0]), origin[1]-(y*units()[1])}; } int (*Graph::from_graph(int x, int y))[1] { return *{((x-origin[0])/units[0]), -((origin[1]-y)/units[1])}; } void Graph::update() { input(); draw_axis(); for (int i = 0; i < origin[0]; ++i) { if ((i % scale) == 0) { // x = 0, y > 0 screen->set_pixel(origin[0] + 2, origin[1] - i, BLACK); screen->set_pixel(origin[0] + 1, origin[1] - i, BLACK); screen->set_pixel(origin[0] - 1, origin[1] - i, BLACK); screen->set_pixel(origin[0] - 2, origin[1] - i, BLACK); // x = 0, y < 0 screen->set_pixel(origin[0] + 2, i + origin[1], BLACK); screen->set_pixel(origin[0] + 1, i + origin[1], BLACK); screen->set_pixel(origin[0] - 1, i + origin[1], BLACK); screen->set_pixel(origin[0] - 2, i + origin[1], BLACK); // y = 0, x > 0 screen->set_pixel(origin[0] - i, origin[1] + 2, BLACK); screen->set_pixel(origin[0] - i, origin[1] + 1, BLACK); screen->set_pixel(origin[0] - i, origin[1] - 1, BLACK); screen->set_pixel(origin[0] - i, origin[1] - 2, BLACK); // y = 0, x < 0 screen->set_pixel(i + origin[0], origin[1] + 2, BLACK); screen->set_pixel(i + origin[0], origin[1] + 1, BLACK); screen->set_pixel(i + origin[0], origin[1] - 1, BLACK); screen->set_pixel(i + origin[0], origin[1] - 2, BLACK); } } } void Graph::draw_axis() { screen->draw_line(origin[0], 0, origin[0], height, BLACK); screen->draw_line(0, origin[1], width, origin[1], BLACK); } void Graph::input() { SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: running = false; break; case SDL_KEYDOWN: in->set_key_down(event.key.keysym.sym); break; case SDL_KEYUP: in->set_key_up(event.key.keysym.sym); break; } } if (in->get_key(SDLK_ESCAPE)) running = false; if (in->get_key(SDLK_MINUS)) zoom_out(); if (in->get_key(SDLK_EQUALS)) zoom_in(); } void Graph::zoom_in() { if (scale < origin[0]) scale += 1; } void Graph::zoom_out() { if (scale > 2) scale -= 1; } <|endoftext|>
<commit_before>#include "all.h" void Graph::addNoodle(Noodle *n, Endpoint from, Endpoint to) { if (m_blocks.find(from.block) == m_blocks.end()) { debug("- block %s(%p) is not in the graph; adding now.\n", from.block->name(), from.block); bool result = m_blocks.insert(from.block).second; assert(result); } else { debug("- block %s(%p) is already in the graph.\n", from.block->name(), from.block); } if (m_blocks.find(to.block) == m_blocks.end()) { debug("- block %s(%p) is not in the graph; adding now.\n", to.block->name(), to.block); bool result = m_blocks.insert(to.block).second; assert(result); } else { debug("- block %s(%p) is already in the graph.\n", to.block->name(), to.block); } debug("- attempting to connect noodle.\n"); /* the connect functions will ensure that this is not a duplicate noodle and * that inputs are not connected to multiple noodles */ from.block->outputs.connect(from.port, n); to.block->inputs.connect(to.port, n); debug("- adding noodle to the graph.\n"); bool result = m_noodles.insert(n).second; assert(result); dumpGraph(); m_needCheck = true; } void Graph::addQNoodle(size_t queue_max, Endpoint from, Endpoint to) { debug("addQNoodle: %s[%s](%p) >>[q:%zu]>> %s[%s](%p)\n", from.block->name(), from.port, from.block, queue_max, to.block->name(), to.port, to.block); QNoodle *n = new QNoodle(queue_max, from, to); addNoodle(n, from, to); } void Graph::addRNoodle(int init, Endpoint from, Endpoint to) { debug("addRNoodle: %s[%s](%p) >>[r:%d]>> %s[%s](%p)\n", from.block->name(), from.port, from.block, init, to.block->name(), to.port, to.block); RNoodle *n = new RNoodle(init, from, to); addNoodle(n, from, to); } void Graph::checkGraph(void) { if (!m_needCheck) return; debug("checkGraph: checking graph validity\n"); if (m_noodles.empty()) { throw EmptyGraphException(); } // TODO: check for nodes with no edges (error) [is this possible?] m_needCheck = false; } void Graph::dumpGraph(void) { static int count = 0; /* don't waste time accessing stuff that we won't print */ if (!verbose) return; debug(AT_BLD AT_ULI "\nGRAPH SNAPSHOT #%d\n" AT_RST, ++count); for (auto it = m_blocks.cbegin(); it != m_blocks.cend(); ++it) { Block *b = *it; debug(" BLOCK " AT_BLD "%s" AT_RST, str_block(b)); auto in_begin = b->inputs.m_names.cbegin(); auto in_end = b->inputs.m_names.cend(); for (auto in_it = in_begin; in_it != in_end; ++in_it) { pair<const char *, int> name = *in_it; unsigned long num_noodles = b->inputs.m_ports.at(b->inputs.m_names.at(name.first)).size(); debug("\n in " AT_ULI FG_GRN "%s" AT_RST FG_DEF, name.first); if (num_noodles > 0) { debug(" (" AT_BLD "%lu" AT_RST " noodle%s)", num_noodles, (num_noodles == 1 ? "" : "s")); } else { debug(" (" FG_RED "unconnected!" FG_DEF ")"); } } auto out_begin = b->outputs.m_names.cbegin(); auto out_end = b->outputs.m_names.cend(); for (auto out_it = out_begin; out_it != out_end; ++out_it) { pair<const char *, int> name = *out_it; unsigned long num_noodles = b->outputs.m_ports.at(b->outputs.m_names.at(name.first)).size(); debug("\n out " AT_ULI FG_RED "%s" AT_RST FG_DEF, name.first); if (num_noodles > 0) { debug(" (" AT_BLD "%lu" AT_RST " noodle%s)", num_noodles, (num_noodles == 1 ? "" : "s")); } else { debug(" (" AT_BLD "unconnected!" AT_RST ")"); } } debug("\n\n"); } for (auto it = m_noodles.cbegin(); it != m_noodles.cend(); ++it) { Noodle *n = *it; debug(" NOODLE %s: %s >>> %s", str_noodle(n), str_endpoint(&n->m_from, false), str_endpoint(&n->m_to, true)); if (n->is_qnoodle()) { auto q = dynamic_cast<QNoodle *>(n); debug("\n fill " AT_BLD "%zu" AT_RST "/" AT_BLD "%zu" AT_RST "\n queue {" AT_BLD, q->count(), q->m_max); deque<int>& qq = q->m_queue; for (auto q_it = qq.cbegin(); q_it != qq.cend(); ++q_it) { debug(" %d", *q_it); } debug(AT_RST " }"); } else { auto r = dynamic_cast<RNoodle *>(n); debug("\n reg " AT_BLD "%d" AT_RST, r->m_reg.load()); } debug("\n\n"); } /* clean up dynamically allocated strings */ m_strpool.clear(); } const char *Graph::str_noodle(const Noodle *n) { char *str = m_strpool.alloc(m_strlen); if (n->is_qnoodle()) { snprintf(str, m_strlen, AT_BLD FG_YLW "QNoodle" AT_RST FG_DEF "@" AT_BLD "%04" PRIxPTR AT_RST, ((uintptr_t)n & 0xffff)); } else { snprintf(str, m_strlen, AT_BLD FG_MGT "RNoodle" AT_RST FG_DEF "@" AT_BLD "%04" PRIxPTR AT_RST, ((uintptr_t)n & 0xffff)); } return str; } const char *Graph::str_block(const Block *b) { char *str = m_strpool.alloc(m_strlen); snprintf(str, m_strlen, AT_BLD FG_CYN "%s" AT_RST FG_DEF "@" AT_BLD "%04" PRIxPTR AT_RST, b->name(), ((uintptr_t)b & 0xffff)); return str; } const char *Graph::str_endpoint(const Endpoint *e, bool input) { char *str = m_strpool.alloc(m_strlen); snprintf(str, m_strlen, AT_BLD FG_CYN "%s" AT_RST FG_DEF "@" AT_BLD "%04" PRIxPTR AT_RST "[" AT_ULI "%s%s" AT_RST FG_DEF "]", e->block->name(), ((uintptr_t)e->block & 0xffff), (input ? FG_GRN : FG_RED), e->port); return str; } <commit_msg>modify styling of rnoodle register contents<commit_after>#include "all.h" void Graph::addNoodle(Noodle *n, Endpoint from, Endpoint to) { if (m_blocks.find(from.block) == m_blocks.end()) { debug("- block %s(%p) is not in the graph; adding now.\n", from.block->name(), from.block); bool result = m_blocks.insert(from.block).second; assert(result); } else { debug("- block %s(%p) is already in the graph.\n", from.block->name(), from.block); } if (m_blocks.find(to.block) == m_blocks.end()) { debug("- block %s(%p) is not in the graph; adding now.\n", to.block->name(), to.block); bool result = m_blocks.insert(to.block).second; assert(result); } else { debug("- block %s(%p) is already in the graph.\n", to.block->name(), to.block); } debug("- attempting to connect noodle.\n"); /* the connect functions will ensure that this is not a duplicate noodle and * that inputs are not connected to multiple noodles */ from.block->outputs.connect(from.port, n); to.block->inputs.connect(to.port, n); debug("- adding noodle to the graph.\n"); bool result = m_noodles.insert(n).second; assert(result); dumpGraph(); m_needCheck = true; } void Graph::addQNoodle(size_t queue_max, Endpoint from, Endpoint to) { debug("addQNoodle: %s[%s](%p) >>[q:%zu]>> %s[%s](%p)\n", from.block->name(), from.port, from.block, queue_max, to.block->name(), to.port, to.block); QNoodle *n = new QNoodle(queue_max, from, to); addNoodle(n, from, to); } void Graph::addRNoodle(int init, Endpoint from, Endpoint to) { debug("addRNoodle: %s[%s](%p) >>[r:%d]>> %s[%s](%p)\n", from.block->name(), from.port, from.block, init, to.block->name(), to.port, to.block); RNoodle *n = new RNoodle(init, from, to); addNoodle(n, from, to); } void Graph::checkGraph(void) { if (!m_needCheck) return; debug("checkGraph: checking graph validity\n"); if (m_noodles.empty()) { throw EmptyGraphException(); } // TODO: check for nodes with no edges (error) [is this possible?] m_needCheck = false; } void Graph::dumpGraph(void) { static int count = 0; /* don't waste time accessing stuff that we won't print */ if (!verbose) return; debug(AT_BLD AT_ULI "\nGRAPH SNAPSHOT #%d\n" AT_RST, ++count); for (auto it = m_blocks.cbegin(); it != m_blocks.cend(); ++it) { Block *b = *it; debug(" BLOCK " AT_BLD "%s" AT_RST, str_block(b)); auto in_begin = b->inputs.m_names.cbegin(); auto in_end = b->inputs.m_names.cend(); for (auto in_it = in_begin; in_it != in_end; ++in_it) { pair<const char *, int> name = *in_it; unsigned long num_noodles = b->inputs.m_ports.at(b->inputs.m_names.at(name.first)).size(); debug("\n in " AT_ULI FG_GRN "%s" AT_RST FG_DEF, name.first); if (num_noodles > 0) { debug(" (" AT_BLD "%lu" AT_RST " noodle%s)", num_noodles, (num_noodles == 1 ? "" : "s")); } else { debug(" (" FG_RED "unconnected!" FG_DEF ")"); } } auto out_begin = b->outputs.m_names.cbegin(); auto out_end = b->outputs.m_names.cend(); for (auto out_it = out_begin; out_it != out_end; ++out_it) { pair<const char *, int> name = *out_it; unsigned long num_noodles = b->outputs.m_ports.at(b->outputs.m_names.at(name.first)).size(); debug("\n out " AT_ULI FG_RED "%s" AT_RST FG_DEF, name.first); if (num_noodles > 0) { debug(" (" AT_BLD "%lu" AT_RST " noodle%s)", num_noodles, (num_noodles == 1 ? "" : "s")); } else { debug(" (" AT_BLD "unconnected!" AT_RST ")"); } } debug("\n\n"); } for (auto it = m_noodles.cbegin(); it != m_noodles.cend(); ++it) { Noodle *n = *it; debug(" NOODLE %s: %s >>> %s", str_noodle(n), str_endpoint(&n->m_from, false), str_endpoint(&n->m_to, true)); if (n->is_qnoodle()) { auto q = dynamic_cast<QNoodle *>(n); debug("\n fill " AT_BLD "%zu" AT_RST "/" AT_BLD "%zu" AT_RST "\n queue {" AT_BLD, q->count(), q->m_max); deque<int>& qq = q->m_queue; for (auto q_it = qq.cbegin(); q_it != qq.cend(); ++q_it) { debug(" %d", *q_it); } debug(AT_RST " }"); } else { auto r = dynamic_cast<RNoodle *>(n); debug("\n reg [ " AT_BLD "%d" AT_RST " ]", r->m_reg.load()); } debug("\n\n"); } /* clean up dynamically allocated strings */ m_strpool.clear(); } const char *Graph::str_noodle(const Noodle *n) { char *str = m_strpool.alloc(m_strlen); if (n->is_qnoodle()) { snprintf(str, m_strlen, AT_BLD FG_YLW "QNoodle" AT_RST FG_DEF "@" AT_BLD "%04" PRIxPTR AT_RST, ((uintptr_t)n & 0xffff)); } else { snprintf(str, m_strlen, AT_BLD FG_MGT "RNoodle" AT_RST FG_DEF "@" AT_BLD "%04" PRIxPTR AT_RST, ((uintptr_t)n & 0xffff)); } return str; } const char *Graph::str_block(const Block *b) { char *str = m_strpool.alloc(m_strlen); snprintf(str, m_strlen, AT_BLD FG_CYN "%s" AT_RST FG_DEF "@" AT_BLD "%04" PRIxPTR AT_RST, b->name(), ((uintptr_t)b & 0xffff)); return str; } const char *Graph::str_endpoint(const Endpoint *e, bool input) { char *str = m_strpool.alloc(m_strlen); snprintf(str, m_strlen, AT_BLD FG_CYN "%s" AT_RST FG_DEF "@" AT_BLD "%04" PRIxPTR AT_RST "[" AT_ULI "%s%s" AT_RST FG_DEF "]", e->block->name(), ((uintptr_t)e->block & 0xffff), (input ? FG_GRN : FG_RED), e->port); return str; } <|endoftext|>